2017-03-20 45 views
0

我有一個程序,它正在寫入一個保存文件。它目前通過檢查一個列表框並簡單地在文本文件中記下它的內容來做到這一點。C#如何檢測文本文件中兩個字符串是否相同

我想要的是,如果文本文件在文本文件中檢測到2個相同的字符串,它將刪除其中的一個。

path = @"C:\thing.txt"; 
if (!File.Exists(path)) 
{ 
    FileStream fs = File.Create(path); 
    fs.Close(); 
} 

if (checkedListBox1.Items.Count > 0) 
{ 
    using (TextWriter tw = File.AppendText(path)) 
    { 
     foreach (string fileName in fullFileName) 
     { 
      foreach (string item in checkedListBox1.Items) 
       tw.WriteLine(fileName); //writes file path to textfile 
     } 
    } 
} 
else 
{ 
    //nothing to do! There is nothing to save! 
} 

而且可以說,在文本文件,包含此:

C:\Jack.exe 
C:\COolstuff.exe 

我不想文本文件有

C:\Jack.exe 
C:\COolstuff.exe 
C:\Jack.exe 

相反,我希望它刪除第三行: C:\ Jack.exe,因爲它匹配第一行。

+0

他們都扔一個列表,你讀不愚弄添加到列表中。將列表內容寫入您的文本文件。 – Trey

+0

因爲一件事情不會多次寫入 - 每個複選框檢查一次:) –

+0

'fullFileName'從哪裏來? –

回答

3

沒有看到你的代碼的其餘部分我相信你可以使用LINQ的Distinct()來快速完成。

foreach (string fileName in fullFileName.Distinct()) 

這將導致foreach只返回唯一的字符串。請記住,您可能需要添加對LINQ名稱空間的引用。如果您在Distinct()上出現錯誤,請將光標放在上面,並使用ctrl+,讓VS爲您提供建議。

+0

可悲的是,不起作用。代碼中沒有錯誤。它只是將相同的內容複製下來兩次。 –

+0

@RohanPas這就是我在對你的問題發表評論時的意思 - 不要多寫幾遍。您選擇一個文件名並在複選框被選中的情況下多次寫入 –

0

如果您想要刪除文本文件中的重複項,您可以執行的操作是讀取數組中的所有行,而不是將其更改爲List,以便您可以使用Distinct(),然後使用新列表重寫爲您的文本文件,如下所示:

string[] lines = File.ReadAllLines(filePath); 

List<string> list = lines.ToList(); 

list = list.Distinct().ToList(); 

File.WriteAllLines(filePath, list.ToArray()); 

有關Distinct的更多信息。

0

如果我理解正確,因爲您只想保存唯一值,那麼先讀取保存的值可能會比較好,以便將它們與新的值進行比較。

代碼流會看起來像:

  1. 是否保存文件存在嗎?
    • 沒有 - >創建空文件名列表
    • 是 - >讀取文件內容保存到文件名列表
  2. 對於每個項目在選中列表框中
    • 如果文件名列表不包含它,將其添加到新文件列表
  3. 將newFiles列表的內容追加到文件

在實踐中,這可能是這樣的:

string saveFilePath = @"c:\data\savedFiles.txt"; 
List<string> savedFileNames = new List<string>(); 
List<string> newFileNames = new List<string>(); 

// If our save file exists, read all contents into the 'saved file' list 
if (File.Exists(saveFilePath)) 
{ 
    savedFileNames.AddRange(File.ReadAllLines(saveFilePath)); 
} 

// For each item in our check box, add it to our 'new 
// file' list if it doesn't exist in the 'saved file' list 
foreach (var checkedItemin CheckedListBox1.CheckedItems) 
{ 
    if (!savedFileNames.Contains(checkedItem)) 
    { 
     newFileNames.Add(checkedItem.ToString()); 
    } 
} 

// Append our new file names to the end of the saved file (this 
// will also create the file for us if it doesn't already exist) 
File.AppendAllLines(saveFilePath, newFileNames); 
相關問題