Sharing violation IOException while reading and writing to file C#
Asked Answered
E

5

23

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

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.

Eckardt answered 18/7, 2012 at 12:22 Comment(1)
You should definitely wrap your streams in using blocks.Melodymeloid
B
25

Well, you're trying to open the file file_no.txt for reading and for 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.

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.

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.

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.

The possibilities are endless :-D

Bemuse answered 18/7, 2012 at 12:26 Comment(1)
Changing FileShare option to ReadWrite instead of none when creating FileStream FileShare.ReadWrite worked for me. FileStream fileStream = new FileStream(fullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);Sletten
A
8

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);
}
Archduchy answered 19/8, 2017 at 4:58 Comment(0)
K
2

Screenshot

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.

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

Kyrakyriako answered 17/5, 2018 at 8:27 Comment(1)
Please don't post images of codes/exception here. It's always better to include them as text.Lauricelaurie
S
1

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.

Submersed answered 22/1, 2021 at 18:36 Comment(0)
S
0

Set FileShare option to ReadWrite

FileStream fileStream = new FileStream(fullName,
                                         FileMode.OpenOrCreate,
                                         FileAccess.ReadWrite,
                                          FileShare.ReadWrite);

  string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
  string fullName = Path.Combine(path, "BarData.json"); 
           
    
            if (!File.Exists(fullName)) 
            {
              //create filestream
              FileStream fileStream = new FileStream(fullName,
                                             FileMode.OpenOrCreate,
                                             FileAccess.ReadWrite,
                                              FileShare.ReadWrite);
    

    
              await JsonSerializer.SerializeAsync(fileStream, barChartData);
              fileStream.Dispose();//async
            }
    
            string filedata = File.ReadAllText(fullName);
Sletten answered 6/6, 2023 at 3:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.