I am trying to check if a CSV file exists and then save it to a MySQL table
Here is the code I have
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);
}
}
}
}
}
It's this line that give me the error
foreach (var fi in diFileCheck.GetFiles())
The message says
"The directory name is invalid.\\r\\n"
I've just noticed my diFileCheck gives an error when I step into it:
Ok here's what I've done and seems to act as I want it to
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);
}
}
}
Thanks for all the tips!
Check to see if the directory exists first using DirectoryInfo.Exists
.
DirectoryInfo diFileCheck = new DirectoryInfo(strDirectory);
if(!diFileCheck.Exists)
// do something here, possibly return
foreach (var fi in diFileCheck.GetFiles())
{
// and so on
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.