我想删除行末尾的空格,然后将该行写入另一个文件。文件无法访问,因为它正在被另一个程序使用
但是当程序到达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();
}
}
那么,该文件显然是由另一个程序打开的。如果它作为窗口打开,也许尝试关闭它?也许另一个程序打开就像你正在尝试? – SimpleVar 2012-07-31 12:08:54
有人猜测,因为您将activeDir和filePaths设置为相同的目录,您正试图写入正在读取的同一文件。 – StuartLC 2012-07-31 12:10:06
那么我试着另一个目录..但同样的错误 – 2012-07-31 12:11:28