gpt4 book ai didi

C# - StreamReader/StreamWriter - 另一个进程使用的文件

转载 作者:太空宇宙 更新时间:2023-11-03 11:03:59 27 4
gpt4 key购买 nike

首先,我确保正确处理和关闭所有内容(包括读取器和写入器)。我做的方法是使用using语句;而在此之前,我手动使用了编写者和读者提供的dispose和close方法。这两种方法都不能解决问题。其次,也是我怀疑的一点,我正在处理大量的读写文件。此外,每次我运行该程序时,该程序都会更深入地运行到应该处理的文件列表中(即,我有 10 个文件,我第一次运行该程序时,它会处理前 2 个,然后再抛出错误;我第二次运行该程序时,它将在抛出错误之前处理前 5 个,依此类推)。那么我应该如何解决这个问题/错误?提前致谢!

编辑 - 附加代码

    public static void FileProcessing(string initPath, string targetPath, string startLine)
{
string line = null;
string content = null;
string nl = "\r\n";
using (StreamReader reader = new StreamReader(initPath))
{
while (!reader.ReadLine().Contains(startLine)) ;

while (!reader.EndOfStream)
{
line = reader.ReadLine();
// Ignore empty line.
if (line.Length > 0)
{
if (!line.Contains("<div"))
content += line += nl;
else
break;
}
}
}

using (StreamWriter writer = new StreamWriter(targetPath))
{
writer.Write(content.Trim());
}
}

/// <summary>
/// Create a temporary text file that correspond to the calendar department page
/// and return the path.
/// </summary>
public static string CreateFile(string path, string title)
{
string npath = path + title + ".txt";
if (!File.Exists(npath))
File.CreateText(npath);
return npath;
}

/// <summary>
/// Return the title of the page.
/// </summary>
/// <param name="path"></param>
public static string GetTitle(string path)
{
string line;
using (StreamReader reader = new StreamReader(path))
{
for (int i = 0; i < 31; ++i)
{
line = reader.ReadLine();
// Ignore empty line.
if (line.Length > 0)
{
if (line.Contains("<h1>"))
{
return line.Slice(4, -5);
}
}
}
return "null";
}
}


/// <summary>
/// Get content from temp path and
/// output the processed text to destination path.
/// </summary>
/// <param name="tempPath"></param>
/// <param name="title"></param>
public static void WriteProcessedText(string tempPath, string targetPath)
{
string content = null;
using (StreamReader reader = new StreamReader(tempPath))
{
string nl = "\r\n";
string line = null;
while (!reader.EndOfStream)
{
line = HtmlRemoval.StripTagsRegex(reader.ReadLine()) + nl;
if (line.Contains("&nbsp;"))
line = line.Replace("&nbsp;", " ");
content += line;
}
}

using (StreamWriter writer = new StreamWriter(targetPath))
{
writer.Write(content.Trim());
}
}

最佳答案

File.CreateText(npath) 不仅在磁盘上创建文件名,而且打开它。因此,要么在 CreateFile 方法中关闭它,要么将其更改为返回一个流。

public static string CreateFile(string path, string title)
{
string npath = path + title + ".txt";
if (!File.Exists(npath))
File.CreateText(npath); //<-- File is not closed !!!
return npath;
}

关于C# - StreamReader/StreamWriter - 另一个进程使用的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16663470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com