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