Replacing Strings in C # Lists

I encoded a program that stores the names and age of students (name, surname, age in a TXT file). Now I am doing the “delete student” part, and when I want the user to choose which name to remove (which is printed by disabling the .txt extension of the file names), it does not replace the “.txt” part with anything. Code:

    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();

If fileNames is List<string>, this is the parameter for the method in which this code resides. studentNames is also List<string>where it stores the names (file name without .txt), but it still prints the name with .txt for some reason.
In short, it does not replace ".txt"with "".

+4
source share
4

, String.Replace ,

file = file.Replace(".txt", "");

file = Path.GetFileNameWithoutExtension(file);

Path.GetFileNameWithoutExtension , , :)

+9

String.Replace . , . :

file = file.Replace(".txt", "");

Path.GetFileNameWithoutExtension

file = Path.GetFileNameWithoutExtension(file);
+3

".txt" :

...
foreach (string file in fileNames)
{
    file = file.Replace(".txt", "");
    studentNames.Add(file);
    Console.WriteLine(file); // debug
}
...
+3
string.Replace();

Does not modify a string that returns a copy. Another problem is that foreach iterators are only readable , so you need something like this.

fileNames = fileNames.Select
            (Path.GetFileNameWithoutExtension);

Hope this helps!

+1
source

All Articles