Search code examples
c#streamreaderstreamwriter

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!


Solution

  • 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