c# - 如何克服以下错误:System.IO.IOException:'目录名称无效。在我的 foreach 循环中?
问题描述
我正在尝试检查 CSV 文件是否存在,然后将其保存到 MySQL 表中
这是我的代码
public void SaveCsvToDatabase(string strDirectory)
{
if (strDirectory.Length > 0)
{
if (ConnectToDatabase())
{
//And specify the name of the file in the path we want.
DirectoryInfo diFileCheck = new DirectoryInfo(strDirectory);
foreach (var fi in diFileCheck.GetFiles())
{
string strSourceFile = fi.FullName;
if (File.Exists(strSourceFile))
{
//save our file to the database
string strFileInsert = "INSERT INTO InvoiceHdr" +
" (fileName) VALUES ('" + MySqlHelper.EscapeString(strSourceFile) + "')";
MySqlCommand command = new MySqlCommand(strFileInsert, con);
if (command.ExecuteNonQuery() == 1)
{
//we've inserted our row, now get the new id
m_iFileId = command.LastInsertedId;
if (m_iFileId != 0)
{
SaveCsvLines(strSourceFile);
}
ArchiveFile();
}
}
else
{
string strMessage = "No file found in directory: \n\n" + strDirectory;
MessageBox.Show(strMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
正是这条线给了我错误
foreach (var fi in diFileCheck.GetFiles())
消息说
"目录名称无效。\r\n"
解决方案
好的,这就是我所做的,并且似乎按照我的意愿行事
public void SaveCsvToDatabase(string strDirectory)
{
if (ConnectToDatabase())
{
//We need to specify file we are looking to process exists.
int fileCount = Directory.GetFiles(@"\\company\Archive\IN\InvoiceTest\Inbox\").Length;
//And specify the name of the file in the path we want.
DirectoryInfo diFileCheck = new DirectoryInfo(@"\\company\EDIArchive\IN\InvoiceTest\Inbox\");
foreach (var file in diFileCheck.GetFiles())
{
string strSourceFile = file.FullName;
if (File.Exists(strSourceFile))
{
//save our file to the database
string strFileInsert = "INSERT INTO InvoiceHdr" +
" (fileName) VALUES ('" + MySqlHelper.EscapeString(strSourceFile) + "')";
MySqlCommand command = new MySqlCommand(strFileInsert, con);
if (command.ExecuteNonQuery() == 1)
{
//we've inserted our row, now get the new id
m_iFileId = command.LastInsertedId;
if (m_iFileId != 0)
{
SaveCsvLines(strSourceFile);
}
ArchiveFile();
}
}
}
if (fileCount == 0)
{
//If we cant count any files in the specified path, we can display a message box warning us.
string strMessage = "No file found in directory: \n\n" + strDirectory;
MessageBox.Show(strMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
感谢所有的提示!