Close file (is being used by another process)

Asked

Viewed 9,903 times

1

The code I am trying to use is the following (I modified only the path and the content), before these lines I do a check if the file does not exist, ie it only executes it if the file does not exist (not to overwrite the same)

File.Create("caminho-arq"); // cria arquivo
File.OpenWrite("caminho-arq"); // abre arquivo para edição
File.WriteAllText("caminho-arq", "conteudo\r\nvai\r\naqui"); // escreve no arquivo
// \r\n começa uma nova linha no arquivo 

The line of File.OpenWrite was my last attempt, even without it does not work, gives error saying "The file 'path-Arq' can not be changed, because it is already being used in another process." Yesterday I faced the same problem, but it wasn’t creating the file, because it was already created, it was meant to read, then save. So I used the StreamRead, I read and took information and closed the file, then used the File.WriteAllText to add new information.. But I don’t know how to do it, there is no File.Close() to close the file

1 answer

5


That line File.Create("caminho-arq"); creates the file and returns a FileStream so you can use, if you’re not going to use you have to close it before opening a new.

File.Create("caminho-arq").Close();

You need to decide which method to use, because your first 2 lines open a FileStream this will always generate conflict to access the file.


The best way to write the file

using(StreamWriter sw = File.AppendText("caminho-arq"))
{                                
    sw.WriteLine("teste");                     
    sw.WriteLine("123");         
}

The method .AppendText() returns a StreamWriter and calf the file if it does not exist, then you do not need to worry to see if it already exists or not. And how you are using the using in Stream he automatically gives a .Close() when you leave the }.

  • Thanks, I would never think that only one was missing. Close() at the end.. Yes, I used the two just as last try, I knew it wouldn’t work.. I deleted the Openwrite line and added . Close() in Create and it worked perfectly. I’m just waiting here for the time to choose as the right answer :)

  • @Leonardovilarinho I improved the answer :)

  • 1

    I agree using(StreamWriter sw = File.AppendText("caminho-arq")) is the best way +1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.