![](/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.