我想刪除行末尾的空格,然後將該行寫入另一個文件。文件無法訪問,因爲它正在被另一個程序使用
但是當程序到達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