Given a filesystem path, is there a shorter way to extract the filename without its extension?

后端 未结 11 854
面向向阳花
面向向阳花 2020-11-22 09:31

I program in WPF C#. I have e.g. the following path:

C:\\Program Files\\hello.txt

and I want to extract hello

相关标签:
11条回答
  • 2020-11-22 09:41

    You can use Path API as follow:

     var filenNme = Path.GetFileNameWithoutExtension([File Path]);
    

    More info: Path.GetFileNameWithoutExtension

    0 讨论(0)
  • 2020-11-22 09:42

    try

    fileName = Path.GetFileName (path);
    

    http://msdn.microsoft.com/de-de/library/system.io.path.getfilename.aspx

    0 讨论(0)
  • 2020-11-22 09:43

    Try this:

    string fileName = Path.GetFileNameWithoutExtension(@"C:\Program Files\hello.txt");
    

    This will return "hello" for fileName.

    0 讨论(0)
  • 2020-11-22 09:45

    try

    System.IO.Path.GetFileNameWithoutExtension(path); 
    

    demo

    string fileName = @"C:\mydir\myfile.ext";
    string path = @"C:\mydir\";
    string result;
    
    result = Path.GetFileNameWithoutExtension(fileName);
    Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", 
        fileName, result);
    
    result = Path.GetFileName(path);
    Console.WriteLine("GetFileName('{0}') returns '{1}'", 
        path, result);
    
    // This code produces output similar to the following:
    //
    // GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
    // GetFileName('C:\mydir\') returns ''
    

    https://msdn.microsoft.com/en-gb/library/system.io.path.getfilenamewithoutextension%28v=vs.80%29.aspx

    0 讨论(0)
  • 2020-11-22 09:46
    string Location = "C:\\Program Files\\hello.txt";
    
    string FileName = Location.Substring(Location.LastIndexOf('\\') +
        1);
    
    0 讨论(0)
  • 2020-11-22 09:47

    Try this,

    string FilePath=@"C:\mydir\myfile.ext";
    string Result=Path.GetFileName(FilePath);//With Extension
    string Result=Path.GetFileNameWithoutExtension(FilePath);//Without Extension
    
    0 讨论(0)
提交回复
热议问题