开发者

How i get a name without the last 4 charecter using C# substring?

开发者 https://www.devze.com 2022-12-31 07:22 出处:网络
Using this below code i get the name only first 4 character.But i need the name except the last 4 character.

Using this below code i get the name only first 4 character.But i need the name except the last 4 character.

string fileName = Textbox1.text;
string newName = fileName.Substring(0, 4);
开发者_StackOverflow

//ex: input abcdef.txt //output:abcd

But i need output: abcdef

pls help!

thanks Riad


I suppose what you really need is a file name without extension. For that, there's a separate method called, naturally, GetFileNameWithoutExtension.


I think that what you are really looking for is Path.GetFileNameWithoutExtension.

// prints abcdef
Console.WriteLine(Path.GetFileNameWithoutExtension("abcdef.txt"));


string newName = fileName.Substring(0, fileName.Length - 4);

Of course, that only works if your extension is 3 characters long (and there is an extension).


string newName = fileName.Substring(0, fileName.Length-4);


In addition to what's already been said, and for anyone interested, there is nothing magical about the System.IO.Path.GetFileNameWithoutExtension method. It simply looks for the last . in the full filename using LastIndexOf().

So all it does under the hood is:

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消