[SOLVED!] See Rupertavery comment
Hi!
I’m trying to edit the ini file.
The goal is to read the file and check if it contains “Mute” in the lines.
If it exists – replace the ending of Mute to make it Mute = False (it could be “Mute = True” initially or the entire line may not exist at all)
If the string with “Mute” in it not exists, I want to add the entire string to the file which will look like “Mute = False”
The code below should work, but I’m getting an access violation thrown by File.AppendAllText(@".\engine\config\platform\pc\user.ini", "Mute = True" + Environment.NewLine);
despite it has “using” in the beginning and seems like nothing has to be closed/flushed.
Can someone point me on what is wrong here?
Thanks!
using (StreamReader sr = new StreamReader(@".\engine\config\platform\pc\user.ini"))
{
string result = string.Empty;
var lines = File.ReadAllLines(@".\engine\config\platform\pc\user.ini");
foreach (var line in lines)
{
if (line.Contains("Mute = "))
{
var text1 = line.Replace("Mute = ", "True");
result = text1.Trim();
}
else
{
using (StreamWriter streamwrite = new StreamWriter(@".\engine\config\platform\pc\user.ini"))
File.AppendAllText(@".\engine\config\platform\pc\user.ini", "Mute = True" + Environment.NewLine);
}
}
}
I think you do not understand how File.ReadAllLines works. It is a standalone function that does not need StreamReader. The same for StreamWriter and File.AppendAllText.
The File.Read… and File.Write… methods execute in one go and access the file directly. There is no need to open as StreamReader/Writer.
Now you would use Streams if you want to process your file a bit at a time. They acquire a lock on the file inside the scope of using
or until Closed or Disposed.
What’s probably happening is that your StreamReader has a lock on the file.
Remove the Stream stuff.
EDIT:
In your code, line.Replace does not actually update the line in the file.
In this approach we read all the lines, process each one and update it if we find the line we’re looking for.
We do this by creating another list and copying each line we process to the output list.
We also track to see if the line was already found. If not, we add it to the end of the list.
Then we overwrite the entire file using the contents we just read (and modified)
Awesome! It works! Thanks a lot for your help!
It’s because you’re creating those additional readers and writers, you have a writer on it and then call File.AppendAllText (that doesn’t use your writer and sees the file is already open for writing, because you do that with the writer).
You’re not using the streams anywhere, just remove them