【发布时间】:2012-07-31 12:03:06
【问题描述】:
我正在尝试删除行尾的空格,然后该行将写入另一个文件。
但是当程序到达FileWriter 时,它会给我以下错误
进程无法访问,因为它正被另一个进程使用。
代码如下。
private void FrmCounter_Load(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(@"D:\abc", "*.txt", SearchOption.AllDirectories);
string activeDir = @"D:\dest";
System.IO.StreamWriter fw;
string result;
foreach (string file in filePaths)
{
result = Path.GetFileName(file);
System.IO.StreamReader f = new StreamReader(file);
string newFileName = result;
// Combine the new file name with the path
string newPath = System.IO.Path.Combine(activeDir, newFileName);
File.Create(newPath);
fw = new StreamWriter(newPath);
int counter = 0;
int spaceAtEnd = 0;
string line;
// Read the file and display it line by line.
while ((line = f.ReadLine()) != null)
{
if (line.EndsWith(" "))
{
spaceAtEnd++;
line = line.Substring(0, line.Length - 1);
}
fw.WriteLine(line);
fw.Flush();
counter++;
}
MessageBox.Show("File Name : " + result);
MessageBox.Show("Total Space at end : " + spaceAtEnd.ToString());
f.Close();
fw.Close();
}
}
【问题讨论】:
-
嗯,文件显然是被另一个程序打开的。如果它作为窗口打开,也许尝试关闭它?也许另一个程序已经像您尝试的那样打开了?
-
猜测一下,因为您将 activeDir 和 filePaths 设置为同一个目录,所以您正试图写入您正在读取的同一个文件。
-
好吧,我也尝试了另一个目录..但同样的错误