简体   繁体   English

在Appdata文件夹中创建文本文件时遇到异常,其说法是文件正在被另一个进程使用

[英]Getting exception while Creation a text file in Appdata folder, its saying File it is being used by another process

I am writing a text file in Appdata folder, I am creating a folder and creating a text file and in next line I am writing text into the file through StreamWriter. 我在Appdata文件夹中写入文本文件,在创建文件夹并创建文本文件,然后在下一行中通过StreamWriter将文本写入文件。 But here I am getting following exception. 但是在这里,我正在追随异常。

The process cannot access the file 'C:\\sdfdfg\\sdfsd\\AppData\\Roaming\\MyFolder\\myFile.txt' because it is being used by another process. 该进程无法访问文件'C:\\ sdfdfg \\ sdfsd \\ AppData \\ Roaming \\ MyFolder \\ myFile.txt',因为该文件正在被另一个进程使用。

This exception I am getting when I create file, if I run app second time than the app is writing the text into same file. 如果我第二次运行应用程序而不是应用程序将文本写入同一文件,则在创建文件时遇到此异常。

My Code is following 我的代码正在关注

StringBuilder sb=new StringBuilder();
if (!File.Exists(filePath))
{
     File.Create(filePath);
     sb.AppendLine(line);
     using (StreamWriter writer = new StreamWriter(filePath, true))
     {
         writer.Write(sb.ToString());
         writer.Close();
     }
}

I tried another function of File, File.WriteAllText(filePath, textToWrite); 我尝试了File的另一个功能File.WriteAllText(filePath,textToWrite); but it is also performing same way as above StreamWriter is behaving. 但它的执行方式也与上述StreamWriter的方式相同。

The simplest solution is to just leave out File.Create() . 最简单的解决方案是只保留File.Create()

The constructor you're using for your StreamWriter will already create the file if it doesn't exist. 如果不存在,则用于StreamWriter的构造函数将已经创建文件。

Another option is to pass the FileStream that File.Create() returns into an appropriate constructor of StreamWriter . 另一个选择是将File.Create()返回的FileStream传递到StreamWriter的适当构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IO异常 - 另一个进程正在使用的文件(创建目录后无法打开文件) - IO Exception - File being used by another process (Can't open file following directory creation) 下载文件时出现错误:该进程无法访问文件'[filepath]',因为它正在被另一个进程使用 - Getting Error while downloading file: The process cannot access the file '[filepath]' because it is being used by another process 该进程无法访问该文件,因为该文件正在被另一个进程使用 - the process cannot access the file as its being used by another process IO异常:该进程正在由另一个进程zip文件使用 - IO Exception : the process is being used by another process zip file 删除文件时文件正在被另一个进程使用 - File is being used by another process while deleting the file FileSystemWatcher无法访问文件,因为它正在被另一个进程使用 - FileSystemWatcher cannot access file because its being used by another process 如何知道文件的文件夹是否正在被另一个进程使用? - How to know if a folder of file is being used by another process? 文件正在被另一个进程使用 - file being used by another process 例外。 文件正在被另一个进程使用(IMAGE) - Exception. File is being used by another process (IMAGE) C#异常。 文件正由另一个进程使用 - C# exception. File is being used by another process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM