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

Viewed 85731

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 it.

The error I get is:

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

I have tried setting seperate timers to each of the functions but it still does not work. I think the best way would be that the function two does not start until function one ends.

Can you help me achieve this? Thank you very much! Mike

Source code:

public Form1() {
    InitializeComponent();
    System.Timers.Timer timerButtona1 = new System.Timers.Timer();
    timerButtona1.Elapsed += new ElapsedEventHandler(tickTimera1);
    timerButtona1.Interval = 3003;
    timerButtona1.Enabled = true;
}

private async void tickTimera1(object source, ElapsedEventArgs e) {
    function1();
    function2();
}

void function1() {
    List<string> linki = new List<string>();

    linki.Add("https://link1.net/");
    linki.Add("https://link2.net/");
    linki.Add("https://link3.net/");

    List<string> fileNames = new List<string>();

    fileNames.Add("name1");
    fileNames.Add("name2");
    fileNames.Add("name3");

    for (int x = 0; x < fileNames.Count; x++) {
        GET(linki[x], fileNames[x]);
        //System.Threading.Thread.Sleep(6000);
    }
}

async void GET(string link, string fileName) {
    var ODGOVOR = await PRENOS_PODATKOV.GetStringAsync(link);
    File.WriteAllText(@"C:\Users\...\" + fileName + ".txt", ODGOVOR);
}

void function2() {
    string originalText = File.ReadAllText(@"C:\Users\...\fileName.txt", Encoding.Default);
    dynamic modifiedText = JsonConvert.DeserializeObject(originalText);
    //then i then i read from the same text files and use some data from it..
}
6 Answers

In one of the unit tests, I had to create a temp file and then remove it after, and I was getting the above error.

None of the answers worked. Solution that worked was:

var path = $"temp.{extension}";
        using (File.Create(path))
        {
        }


        File.Delete(path);

Create a file and then close it. After can save data into that file. I did as below.

if (!File.Exists(filePath))
{
    File.Create(filePath).Close();
}
File.WriteAllText(filePath, saveDataString)
Related