文件不能被访问,因为它被另一个程序使用 [英] File cannot be accessed because it is being used by another program
问题描述
但是当程序达到<$ c时,这个行会被写入另一个文件。 $ c> FileWriter 然后它给我以下错误
lockquote
进程无法访问,因为它是
代码如下。
<$ p $ ($code> 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;
字符串结果;
foreach(filePaths中的字符串文件)
{
result = Path.GetFileName(file);
System.IO.StreamReader f = new StreamReader(file);
string newFileName = result;
//将新文件名与路径
结合起来newPath = System.IO.Path.Combine(activeDir,newFileName);
File.Create(newPath);
fw = new StreamWriter(newPath);
int counter = 0;
int spaceAtEnd = 0;
字符串行;
//读取文件并逐行显示。 $()
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(总空间在结束:+ spaceAtEnd.ToString());
f.Close();
fw.Close();
$ / code $ / pre
code> File.Create 本身返回一个流。
使用该流写入文件。您收到此错误的原因是因为由 File.Create
返回的Stream已打开,您正试图再次打开该文件进行写入。
关闭由 File.Create
返回的流,或者更好地使用该流进行文件写入或使用
Stream newFile = File.Create(newPath);
fw =新的StreamWriter(newFile);
I am trying to remove the space at the end of line and then that line will be written in another file.
But when the program reaches to FileWriter
then it gives me the following error
Process can't be accessed because it is being used by another process.
The Code is as below.
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();
}
}
File.Create
itself returns a stream.
Use that stream to write file. Reason you are receiving this error is because Stream returned by File.Create
is open and you are trying to open that file again for write.
Either close the stream returned by File.Create
or better use that stream for file write or use
Stream newFile = File.Create(newPath);
fw = new StreamWriter(newFile);
这篇关于文件不能被访问,因为它被另一个程序使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!