我正在.csv文件中生成报告。
我正在使用以下代码通过按钮点击事件的代码打开.csv文件。
StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);
//write header line
int iColCount = TheDataTable.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(TheDataTable.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
//write rows
foreach (DataRow dr in TheDataTable.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string data = dr[i].ToString();
data = data.Replace("\"", "\\\"").Replace(",", " ");
sw.Write(quote + data + quote);
}
if (i < iColCount - 1)
{
sw.Write(separator);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
MsgBox db = new MsgBox("Please select below option.", "Message", MessageBoxIcon.Information);
db.SetButtons("Open Master File", "Save Master File", strBasePath + "\\master.csv");
db.ShowDialog(this);
这段代码对我来说很好。
现在我的文件处于打开模式。如果我过滤另一个标准再次打开报告(.csv文件) 而不是它向我抛出错误,该文件被另一个进程使用。
如何解决该错误?
答案 0 :(得分:0)
ChrisW 对 Is there a way to check if a file is in use?
给出了一个很好的答案您可以使用以下示例代码检查您的文件是否正在使用:
protected virtual bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } //file is not locked return false; }
希望这有帮助。