我一直在编写一个程序,用于存储学生的姓名和年龄(.txt文件中的名字,姓氏,年龄)。我现在正在制作“删除学生”部分,并且当我希望用户选择要删除的名称(通过截断文件名的.txt扩展名打印)时,它不会替换“ .txt”部分一无所有。
代码是:
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();
在fileNames是a的情况下List<string>
,它是此代码所在方法的参数。studentNames也是a List<string>
,用于存储名称(不带.txt的文件名),但由于某些原因它仍显示带.txt的名称。
长话短说,它不会取代".txt"
用""
。
这是因为String.Replace返回值,而不是修改,请参见此处
file = file.Replace(".txt", "");
我建议使用
file = Path.GetFileNameWithoutExtension(file);
Path.GetFileNameWithoutExtension将与所有扩展名一起使用,并且看起来更干净,并说明其中的操作:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句