【发布时间】:2012-09-17 01:20:26
【问题描述】:
我在从控制台应用程序中的大型制表符分隔文本文件读取后尝试写入文本文件。问题是,如果我在服务器上同时运行此 exe 的多个实例,它会在 TextWriter.WriteLine 处给我运行时错误,然后由于未处理的异常而导致应用程序崩溃。所有实例都会发生这种情况。我无法理解这种行为的原因。是因为我没有使用 StringBuilder 会动态使用内存吗?
我的代码如下:
StreamReader sr = new StreamReader(@FilePath, System.Text.Encoding.Default);
string mainLine = sr.ReadLine();
string[] fileHeaders = mainLine.Split(new string[] { "\t" }, StringSplitOptions.None);
string newLine = "";
System.IO.StreamWriter outFileSw = new System.IO.StreamWriter(@outFile);
while (!sr.EndOfStream)
{
mainLine = sr.ReadLine();
string[] originalLine = mainLine.Split(new string[] { "\t" }, StringSplitOptions.None);
newLine = "";
for (int i = 0; i < fileHeaders.Length; i++)
{
if(fileHeaders[i].Trim() != "")
newLine = newLine + fileHeaders[i].Trim() + "=" + originalLine[i].Trim() + "&";
}
outFileSw.WriteLine(newLine.Remove(newLine.Length - 1));
FileInfo fileInfo = new FileInfo(@outFile);
if (fileInfo.Length > (1.3 * 1024.0 * 1024.0 * 1024.0)) // greater than 1.3 GB
{
outFileSw.Close();
outFileNumber = outFileNumber + 1;
outFileSw = new System.IO.StreamWriter(@outFile + outFileNumber.ToString() + ".txt");
}
}
outFileSw.Dispose();
sr.Close();
sr.Dispose();
错误详情是:
Exception Message: The specified network name is no longer available.
Stack Trace: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.FileStream.Write(Byte[] array, Int32 offset, Int32 count)
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Write(Char[] buffer, Int32 index, Int32 count)
at System.IO.TextWriter.WriteLine(String value)
at ExampleExe.ExampleProcess.FnFiles()
Unhandled Exception: System.IO.IOException: The specified network name is no longer available.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.WriteCore(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.FileStream.FlushWrite(Boolean calledFromFinalizer)
at System.IO.FileStream.Dispose(Boolean disposing)
at System.IO.FileStream.Finalize()
谢谢, 卡努
【问题讨论】:
-
你曾经关闭过这些文件吗?
using(){}在这些情况下非常有用。 -
@nrodic:是的。我在处理完我正在阅读的完整文件后关闭并处理。此外,当应用程序尝试写入文件时会发生错误。
-
@nordic:我编辑了问题文本以显示我如何关闭和处置...
-
你写的是网络路径吗?理想情况下,您希望缓冲而不是写入每一行,这会减少原始 IO 的数量。您可以缓冲例如在将内容转储到文件之前,需要 10MB 到 stringbuider 或字节缓冲区。
-
尝试进行网络跟踪和 filemon 跟踪。
标签: c# console-application windows-server-2003 ioexception streamwriter