Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

375
Views
why File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.Read) fails?

My goal is to write to and read same file at same time. I cannot understand why File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read) fails because it is being used by another process. The file is created by my code and I didn't set any special attributes. Tried in both .net framework 4.8 and .net6 console apps.

        static void Main(string[] args)
        {
            const string fileName = "TestFile.txt";
            try
            {
                FileStream ws = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                Console.WriteLine("ws ok");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ws {ex.Message}");
            }

            try
            {
                FileStream rs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                Console.WriteLine("rs ok");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"rs {ex.Message}");
                //rs The process cannot access the file 'debugpath\TestFile.txt' because it is being used by another process.
            }
            //stream close omited
            Console.ReadKey();
        }

Have read the docs FileShare Enum but cannot find any reason. Doesn't FileShare.Read mean share the file or stream with others(threads, processes) to read?

Could anyone explain the reason, and give the correct way to read the file?

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!