How do I open with read-only mode while saving csv file?

112 Views Asked by At

In C#, my program creates *.csv file. And append data to this file every 1ms. While append data, when I open *.csv file, this error occurs I JUST want to open "ONLY READ MODE" while append data in this file.

/* File create */

using (FileStream fileStream = new FileStream(csvFileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (StreamWriter sr = new StreamWriter(fileStream))
                {
                    for (int i = 0; i < 20; i++)
                    {
                        dataArray[i] = data[i];
                    }
                }
            }

/* Data Update */

            using (FileStream fileStream = new FileStream(csvFileName, FileMode.Append, FileAccess.Write, FileShare.Read))
            {
                using (StreamWriter sr = new StreamWriter(fileStream))
                {
                    sr.Write(csv_count++ + ",");
                    for (int i = 0; i < 20; i++)
                    {
                        dataArray[i] = data[i].ToString();
                    }
                    sr.Write(string.Join(",", dataArray));
                }
            }

When I open this *.csv file, this message pop-up. "System.IO.IOException: ''D:\data.csv' The file is not accessible to the process because it is in use by another process.'

2

There are 2 best solutions below

0
Joma On

FileShare.Read / Allow to open file in read mode while is in use by another program.

  • When update / FileMode.Append, FileAccess.Write, FileShare.Read
  • When open / FileMode.Open, FileAccess.Read, FileShare.Read
0
menukim On

Basically, you are reading and writing on a file simultaneously. While you are reading a file, the file would be locked unless you open the stream with FileShare.ReadWrite. Otherwise, the file would also be locked while you are writing on it.

Proper FileShare value is FileShare.ReadWrite.

Checkout MSDN document for details. https://learn.microsoft.com/en-us/dotnet/api/system.io.fileshare?view=net-7.0