Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

376
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda