使用下面的代碼,我只得到名字的前4個字符。但我需要的名字除了最後4個字符。我如何得到一個沒有使用C#子字符串的最後4個字符的名字?
string fileName = Textbox1.text;
string newName = fileName.Substring(0, 4);
//例如:輸入abcdef.txt //輸出:ABCD
但我需要輸出:ABCDEF
請幫助!
感謝 里亞德
使用下面的代碼,我只得到名字的前4個字符。但我需要的名字除了最後4個字符。我如何得到一個沒有使用C#子字符串的最後4個字符的名字?
string fileName = Textbox1.text;
string newName = fileName.Substring(0, 4);
//例如:輸入abcdef.txt //輸出:ABCD
但我需要輸出:ABCDEF
請幫助!
感謝 里亞德
我想你真正需要的是一個沒有擴展名的文件名。爲此,有一種單獨的方法稱爲自然GetFileNameWithoutExtension
。
這也解決了一些擴展名超過3個字符的問題,例如:'index.html' – 2010-05-25 11:47:20
感謝兄弟,這就是我一直在尋找的。 – riad 2010-05-25 12:04:43
我認爲你是什麼真正尋找的是Path.GetFileNameWithoutExtension
。
// prints abcdef
Console.WriteLine(Path.GetFileNameWithoutExtension("abcdef.txt"));
感謝兄弟,這是我一直在尋找。 – riad 2010-05-25 12:05:07
string newName = fileName.Substring(0, fileName.Length-4);
string newName = fileName.Substring(0, fileName.Length - 4);
當然,這只是如果您的分機長3個字符(並且有一個擴展名)的作品。
除了已經說過的內容之外,對於任何感興趣的人來說,System.IO.Path.GetFileNameWithoutExtension
方法並沒有什麼神奇之處。它僅使用LastIndexOf()
查找完整文件名中的最後.
。
因此,所有它的引擎蓋下是:
public static string GetFileNameWithoutExtension(string path)
{
path = GetFileName(path);
if (path == null)
{
return null;
}
int length = path.LastIndexOf('.');
if (length == -1)
{
return path;
}
return path.Substring(0, length);
}
里亞德,你可能不知道這一點,但你可以標記爲您的方案的最佳答案點擊勾選爲「回答說,」留下來的數票。 – 2010-05-25 12:28:32