Reputation: 177
I have a program and it is writing a save file. It currently does this by checking a listbox and simply writing down its contents in a textfile.
What I want is that if the textfile detects 2 identical strings in a text file, it will delete one of them.
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!
}
And lets say that in the textfile, contains this:
C:\Jack.exe
C:\COolstuff.exe
I do not want the textfile to have
C:\Jack.exe
C:\COolstuff.exe
C:\Jack.exe
Instead I want it to delete that third line: C:\Jack.exe since it matches the 1st line.
Upvotes: 0
Views: 152
Reputation: 37020
If I understand you correctly, since you only want to save unique values, then it might be good to read your saved values first so you can compare them to the new ones.
The code flow would look something like:
In practice, this might look like:
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);
Upvotes: 0
Reputation: 2923
What you could do if you want to delete the duplicates in a text file is read all lines in a array than change it to a List so you can use Distinct()
and then rewrite to your text file with the new List like this:
string[] lines = File.ReadAllLines(filePath);
List<string> list = lines.ToList();
list = list.Distinct().ToList();
File.WriteAllLines(filePath, list.ToArray());
More information on Distinct.
Upvotes: 0
Reputation: 1109
Without seeing the rest of your code I believe you can use LINQ's Distinct() to accomplish this quickly.
foreach (string fileName in fullFileName.Distinct())
This will cause foreach
to return only unique strings. Remember you may need to add a reference to the LINQ namespace. If you get an error on Distinct() put your cursor on it and use ctrl+,
to have VS suggest that for you.
Upvotes: 3