-1

i'm trying to create a json file if it doesn't exist, and then write all lines to it. The creation of the file works, but the problem i have is that File.WriteAllLines says "the process cannot access the file because it is being used by another process".

Here's my code:

public void generateFolderFiles(string folderToSearch, string fileToEdit) {
        string[] filesToSearch = Directory.GetFiles(folderToSearch);
        string completeJson = "";
        for(int i=0;i<filesToSearch.Length;i++) {
            try {
                File.Delete(fileToEdit);
                File.Create(fileToEdit);
            } catch(Exception e){}
            string[] fsLines = File.ReadAllLines(filesToSearch[i]);
            string fsText = string.Join("", fsLines);
            fsText=fsText.Replace("[", "").Replace("]", "");
            completeJson+=fsText;
        }
        completeJson="["+completeJson+"]";
        string[] lnes = new string[1]{completeJson};
        File.WriteAllLines(fileToEdit, lnes);
    }
Cryonic
  • 21
  • 4

1 Answers1

2

File.Create() returns a FileStream which you can use to do the file IO. While FileStream is open (and in your case it remains open for who knows how long because you do not call neither Close(), nor Dispose() on it), it does not not allow anybody else to access it (in reality, things are a bit more complex), which is why your WriteAllLines() call fails.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288