简体   繁体   English

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

[英]Sharing violation IOException while reading and writing to file C#

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” 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 I doing wrong.Thanks for help.

Well, you're trying to open the file file_no.txt for reading and for writing using separate streams.那么,您正在尝试打开文件file_no.txt以使用不同的流进行读取写入。 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.这可能不起作用,因为文件将被读取流锁定,因此无法创建写入流,您会得到异常。

One solution would be to read the file first, close the stream and then write the file after increasing the fileNo .一种解决方案是先读取文件,关闭流,然后在增加fileNo后写入文件。 That way the file is only opened once at a time.这样文件一次只能打开一次。

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 question seems 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.txt and log_5.txt , the next file won't be log_6.txt but log_2.txt .缺点:如果您有log_1.txtlog_5.txt ,下一个文件将不是log_6.txt而是log_2.txt

To overcome this, you could enumerate all the files in your directory with mask log_*.txt and find the greatest number by performing some string manipulation.为了克服这个问题,您可以使用掩码log_*.txt枚举目录中的所有文件,并通过执行一些字符串操作找到最大的数字。

The possibilities are endless:-D可能性是无限的:-D

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);
}

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,问题得到解决。

None of the proposed options helped me.提议的选项都没有帮助我。 But I found a solution: In my case, the problem was with Anti-Virus, with intensive writing to a file, Anti-Virus started scanning the file and at that moment there was a problem with writing to the file.但我找到了解决方案:在我的案例中,问题出在反病毒软件上,大量写入文件,反病毒软件开始扫描文件,此时写入文件时出现问题。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM