Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using StreamReader & Writer on same Textfile

I recently run into an issue i wasn't able to find a solution for, that suits my needs. So I am trying to read a textfile line by line and check if the line is a specific string. If the file doesn't contain that string yet it should be written to the file. This is my current approche on this.

int i = 0;
using (var sw = new StreamWriter(this.filePath))
{
    foreach (SimplePlaylist playlist in myPlaylists)
    {
        this.PlaylistTracks[i] = new List<PlaylistTrack>();
        this.PlaylistTracks[i] = GetPlaylistTracks(playlist.Owner.Id, playlist.Id);
        foreach (PlaylistTrack tr in this.PlaylistTracks[i])
        {
            string write = tr.Track.Name + " // " + string.Join(",", tr.Track.Artists.Select(source => source.Name)) + " // " + tr.Track.Album.Id;
            string line = "";
            bool found = false;
            using (var sr = new StreamReader(this.filePath))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Equals(write))
                    {
                        found = true;
                        break;
                    }
                }
                sr.Close();
            }
            if (!found)
            {
                sw.WriteLine(write);
            }
        }
        i++;
    }
    sw.Close();
}

I've read about the problematic of reading and writing to a file at the same time, but i'm wondering if there is a way to achieve this. Any help is appreciated!

like image 324
ZZ_James Avatar asked Mar 08 '26 23:03

ZZ_James


2 Answers

Use a FileStream and use it for both, StreamReader and StreamWriter, here is an example of adding or changing lines of a textFile:

public static void ChangeOrAddLine(string filePath, string newLine, string oldLine = "")
{
    using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
    using (StreamReader sr = new StreamReader(fs))
    using (StreamWriter sw = new StreamWriter(fs))
    {
        List<string> lines = sr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
        fs.Position = 0;
        bool lineFound = false;
        if (oldLine != "")
            for (int i = 0; i < lines.Count; i++)
                if (lines[i] == oldLine)
                {
                    lines[i] = newLine;
                    lineFound = true;
                    break;
                }
        if (!lineFound)
            lines.Add(newLine);
        sw.Write(string.Join("\r\n", lines));
        fs.SetLength(fs.Position);
    }
}

FileAccess.ReadWrite opens the File for reading and writing

FileShare.Read let the be read by other programs as well

Another option not suggested is to open the reader on the original file, a writer on a temp file. Read from the original write to the temp file and add the missing lines, then replace the original file with the temp file.

like image 37
MikeS Avatar answered Mar 11 '26 21:03

MikeS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!