System.IO.IOException: 'The process cannot access the file '@.txt' because it is being used by another process.'

后端 未结 6 601
野的像风
野的像风 2021-01-11 13:15

I am new to programming and I have a question. If I have two functions, one creates a text file and writes into it, while the other opens the same text file and reads from i

6条回答
  •  终归单人心
    2021-01-11 13:31

    after writing your text file, you should close it first before proceeding to your second function:

    var myFile = File.Create(myPath);
    //some other operations here like writing into the text file
    myFile.Close(); //close text file
    //call your 2nd function here
    

    Just to elaborate:

    public void Start() {
        string filename = "myFile.txt";
        CreateFile(filename); //call your create textfile method
        ReadFile(filename); //call read file method
    }
    
    public void CreateFile(string filename) {
        var myFile = File.Create(myPath); //create file
        //some other operations here like writing into the text file
        myFile.Close(); //close text file
    }
    
    public void ReadFile(string filename) {
        string text;
        var fileStream = new FileStream(filename, FileMode.Open, 
        FileAccess.Read); //open text file
        //vvv read text file (or however you implement it like here vvv
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            text = streamReader.ReadToEnd();
        }
        //finally, close text file
        fileStream.Close();
    }
    

    The point is, you have to close the FileStream after you are done with any operations with your file. You can do this via myFileStream.Close().

    Moreover, File.Create(filename) returns a FileStream object which you can then Close().

提交回复
热议问题