I've been coding a program that stores student names and age (First name, last name, age in a .txt file). I am now making the "delete student" part, and when I want the user to select what name to delete (which is printed by cutting off the .txt extension of the filenames), it doesn't replace the ".txt" part with nothing.
The code is:
string inputSel; // Selection string for delete
Console.WriteLine(" -- Deleting Grade {0} -- ", grade);
Console.WriteLine("- Enter a student name to delete: ");
foreach (string file in fileNames)
{
file.Replace(".txt", "");
studentNames.Add(file);
Console.WriteLine(file); // debug
}
foreach (string name in studentNames)
{
Console.Write("{0}\t", name);
}
Console.WriteLine();
Console.Write("> ");
inputSel = Console.ReadLine();
Where fileNames is a List<string>
, it is a parameter for the method this code is in. studentNames is also a List<string>
, where it stores the names (file name without .txt), but it still prints the name with .txt for some reason.
Long story short, it doesn't replace ".txt"
with ""
.
It's because String.Replace returns value, not modifies see here
file = file.Replace(".txt", "");
I suggest using
file = Path.GetFileNameWithoutExtension(file);
Path.GetFileNameWithoutExtension will work with all extensions and it looks cleaner and says what is done there :)
String.Replace
method creates new string. It does not modifies string which you are passing. You should assign result of replacement to your string:
file = file.Replace(".txt", "");
Also I suggest you to use Path.GetFileNameWithoutExtension
to get file name without extension
file = Path.GetFileNameWithoutExtension(file);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With