![](/img/trans.png)
[英]System.IO.IOException: 'The handle is invalid. : '\\.\Con''
[英]How can I get past the following error: System.IO.IOException: 'The directory name is invalid. in my foreach loop?
我正在嘗試檢查 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);
}
}
}
感謝所有的提示!
首先使用DirectoryInfo.Exists
檢查目錄是否存在。
DirectoryInfo diFileCheck = new DirectoryInfo(strDirectory);
if(!diFileCheck.Exists)
// do something here, possibly return
foreach (var fi in diFileCheck.GetFiles())
{
// and so on
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.