我最近碰到一個問題,我無法找到一個解決方案,即適合我的需要使用的StreamReader與作家。所以我試圖逐行閱讀一個文本文件,並檢查該行是否是特定的字符串。如果文件不包含該字符串,則應將其寫入文件。這是我目前對此的讚賞。對同一文本文件
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();
}
我已閱讀有關在同一時間讀取和寫入文件的問題,但我想知道是否有辦法實現這一點。任何幫助表示讚賞!
如何做所有的閱讀第一,創造你需要添加行的列表。然後寫下這些線。閱讀和寫作必須一起完成嗎? – gunnerone
gunnerone,如果文件內容很大,不是一個好方法。我想,這首先是流式傳輸的目的。 – Tilak