Close file (is being used by another process)

1

The code I am trying to use is the following (I just modified the path and content), before these lines I check if the file does not exist, ie it only executes this 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 it does not work, it gives error saying "The file 'path-arq' can not be changed, since it is already being used in another process." Yesterday I faced the same problem, but it was not creating the file, because it was already created, was to read, then save. Then I used StreamRead , read and get information and I closed the file, then I used File.WriteAllText to add new information .. But I do not know how to do it, there is no File.Close() to close the file

    
asked by anonymous 28.06.2015 / 17:22

1 answer

5

This File.Create("caminho-arq"); line creates the file and returns you a FileStream for you to use, if you do not use it you have to close it before opening a new one.

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

You need to decide which method to use, because your first 2 lines open 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 creates the file if it does not exist, so you do not have to worry to see if it already exists or not. And since you are using using in Stream it automatically gives .Close() when it exits } .

    
28.06.2015 / 17:25