c# - 在同一文本文件上使用 StreamReader 和 Writer

标签 c# streamreader streamwriter

我最近遇到了一个问题,我找不到适合我需要的解决方案。所以我试图逐行读取文本文件并检查该行是否是特定字符串。如果文件不包含该字符串,则应将其写入文件。这是我目前的做法。

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();
}

我读过有关同时读取和写入文件的问题,但我想知道是否有办法实现这一点。感谢您的帮助!

最佳答案

使用 FileStream 并将其用于 StreamReader 和 StreamWriter,这里是添加或更改文本文件行的示例:

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 打开文件进行读写

FileShare.Read 让其他程序也能读取

关于c# - 在同一文本文件上使用 StreamReader 和 Writer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42163248/

相关文章:

c# - 流不可写

c# - 列表框中的 StreamReader 和 Writer

c# - MVC View 直接与模型交互 - 好还是坏?

c# - NServiceBus 在非侵入式模式下找不到 Endpoint 或 MessageEndpointMappings

c# - 将窗口设置为在MVVM中隐藏后捕获屏幕

c# - 我怎么知道文本文件是否以回车结尾?

c# - 从 Unity 到 HoloLens 的程序问题 - 无法从 'string' 转换为 'System.IO.Stream'

c# - 从 XML 文件 C# 中删除回车

c# - 带有语句体的 lambda 表达式无法在 nopCommerce 中转换为表达式树

C# 类库 : StreamWriter writing to system32 folder