读取和写入文件 C# 时共享冲突 IOException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11541244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:12:27  来源:igfitidea点击:

Sharing violation IOException while reading and writing to file C#

c#file-iotextreadertextwriter

提问by Ozg

Here is my code:

这是我的代码:

public static TextWriter twLog = null;
private int fileNo = 1;
private string line = null;

TextReader tr = new StreamReader("file_no.txt");
TextWriter tw = new StreamWriter("file_no.txt");
line = tr.ReadLine();
if(line != null){
    fileNo = int.Parse(line);
    twLog = new StreamWriter("log_" + line + ".txt");
}else{
    twLog = new StreamWriter("log_" + fileNo.toString() + ".txt");  
}
System.IO.File.WriteAllText("file_no.txt",string.Empty);
tw.WriteLine((fileNo++).ToString());
tr.Close();
tw.Close();
twLog.Close();

It throws this error:

它抛出这个错误:

IOException: Sharing violation on path C:\Users\Water Simulation\file_no.txt

IOException:在路径 C:\Users\Water Simulation\file_no.txt 上共享冲突

What i'm trying to do is just open a file with log_x.txt name and take the "x" from file_no.txt file.If file_no.txt file is empty make log file's name log_1.txt and write "fileNo + 1" to file_no.txt.After a new program starts the new log file name must be log_2.txt.But i'm getting this error and i couldn't understand what am i doing wrong.Thanks for help.

我想要做的只是打开一个名为 log_x.txt 的文件并从 file_no.txt 文件中取出“x”。如果 file_no.txt 文件为空,则将日志文件的名称设为 log_1.txt 并写入“fileNo + 1”到 file_no.txt。新程序启动后,新的日志文件名必须是 log_2.txt。但我收到此错误,我不明白我做错了什么。感谢您的帮助。

采纳答案by Thorsten Dittmar

Well, you're trying to open the file file_no.txtfor reading andfor writing using separate streams. This may not work as the file will be locked by the reading stream, so the writing stream can't be created and you get the exception.

好吧,您正在尝试使用单独的流打开文件file_no.txt进行读取写入。这可能不起作用,因为文件将被读取流锁定,因此无法创建写入流并且您会收到异常。

One solution would be to read the file first, close the stream and then write the file after increasing the fileNo. That way the file is only opened once at a time.

一种解决方案是先读取文件,关闭流,然后在增加fileNo. 这样文件一次只打开一次。

Another way would be to create a file stream for both read and write access like that:

另一种方法是为读写访问创建一个文件流,如下所示:

FileStream fileStream = new FileStream(@"file_no.txt", 
                                       FileMode.OpenOrCreate, 
                                       FileAccess.ReadWrite, 
                                       FileShare.None);

The accepted answer to this questionseems to have a good solution also, even though I assume you do not want to allow shared reads.

这个问题的公认答案似乎也有一个很好的解决方案,即使我假设您不想允许共享读取。

Possible alternate solution
I understand you want to create unique log files when your program starts. Another way to do so would be this:

可能的替代解决方案
我知道您想在程序启动时创建唯一的日志文件。另一种方法是这样的:

int logFileNo = 1;
string fileName = String.Format("log_{0}.txt", logFileNo);

while (File.Exists(fileName))
{
    logFileNo++;
    fileName = String.Format("log_{0}.txt", logFileNo);
}

This increases the number until it finds a file number where the log file doesn't exist. Drawback: If you have log_1.txtand log_5.txt, the next file won't be log_6.txtbut log_2.txt.

这会增加数字,直到找到日志文件不存在的文件编号。缺点:如果你有log_1.txtand log_5.txt,下一个文件不会是log_6.txtbut log_2.txt

To overcome this, you could enumerate all the files in your directory with mask log_*.txtand find the greatest number by performing some string manipulation.

为了克服这个问题,您可以使用掩码枚举目录中的所有文件,log_*.txt并通过执行一些字符串操作来找到最大数量。

The possibilities are endless :-D

可能性是无限的:-D

回答by Prince Tegaton

Well this may be old but the accepted answer didn't work for me. This is caused when you try to Read or Write a file you just created from a separate stream. Solving this is very simple, just dispose the filestream you used in creating it and then you can access the file freely.

好吧,这可能很旧,但接受的答案对我不起作用。这是在您尝试从单独的流中读取或写入刚刚创建的文件时引起的。解决这个问题很简单,只要把你创建的文件流处理掉,就可以自由访问文件了。

if (!File.Exists(myfile))
{
    var fs = new FileStream(fav, FileMode.Create);
    fs.Dispose();
    string text = File.ReadAllText(myfile);
}

回答by clumsycoder

enter image description here

在此处输入图片说明

         var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);

        resizedBitmap.Compress(Bitmap.CompressFormat.Png, 200, stream); //problem here
        stream.Close();
        return resizedBitmap;

In the Compress method, I was passing the value of the quality parameter as 200, which sadly doesn't allows values outside the range 0-100.

在 Compress 方法中,我将质量参数的值传递为 200,遗憾的是不允许 0-100 范围之外的值。

I changed back the value of quality to 100 and the issue got fixed.

我将质量值改回 100,问题得到解决。