c# - StreamReader/StreamWriter -文件被另一个进程使用
本文关键字:另一个 进程 文件 StreamReader StreamWriter | 更新日期: 2023-09-27 18:14:39
首先,我确保正确地处置和关闭了所有内容(包括读取器和写入器)。我使用的方法是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(" "))
line = line.Replace(" ", " ");
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;
}