【问题标题】:How can I get a 'File Name' ONLY from the (File Name + Extension) using substring in C#? [duplicate]如何使用 C# 中的子字符串仅从(文件名 + 扩展名)中获取“文件名”? [复制]
【发布时间】:2014-01-29 19:23:37
【问题描述】:

这似乎很简单,但我搞不懂。

情况如下:

我有一个完整的文件名,例如 abdcd.pdfefghijf.jpgjklmn.jpeg

现在我只需要将 文件名 设为 abdcdefghijfjklmn

【问题讨论】:

  • 找到'.'的最后一个索引,并将子字符串从开头取到那个索引
  • 说真的,既然Googling the title 也会得到答案,你为什么还要麻烦在这里发布问题......

标签: c# substring


【解决方案1】:

使用Path类静态方法

result = Path.GetFileNameWithoutExtension(fileName);

【讨论】:

    【解决方案2】:
            String f = "file.jpg";
            int lastIndex = f.LastIndexOf('.');
            Console.WriteLine(f.Substring(0, lastIndex));
    

    或者,像其他人建议的那样,您也可以使用

            Path.GetFileNameWithoutExtension(f)
    

    【讨论】:

    • 查找最后一个 '.'如果文件名没有'.',将失败。之后调用Substring(0,-1) 将引发异常。 GetFileNameWithoutExtension 是更好的选择。
    • 是的,你是对的,我认为扩展名一直存在;)
    【解决方案3】:

    您可以使用String.Substring(),但我推荐Path.GetFileNameWithoutExtension() 用于此任务:

    // returns "test"
    Path.GetFileNameWithoutExtension("test.txt")
    

    Go to the msdn documentation

    这个方法本质上是这样实现的:

      int index = path.LastIndexOf('.');
      return index == -1 ? path : path.Substring(0, index);
    

    【讨论】:

      【解决方案4】:

      我会使用 API 调用。

      http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension(v=vs.110).aspx

      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 ''
      

      【讨论】:

        【解决方案5】:

        我会使用 Path 静态方法:Path.GetFileNameWithoutExtension()

        【讨论】:

          【解决方案6】:

          【讨论】:

          • 实际上有一个应用程序!
          【解决方案7】:

          像这样使用GetFileNameWithoutExtension 静态方法:

          result = Path.GetFileNameWithoutExtension(fileName);
          

          来自MSDN

          GetFileName 返回的字符串,减去最后一个句点 (.) 及其后面的所有字符。

          【讨论】:

            猜你喜欢
            • 2010-10-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-12-07
            • 2013-06-02
            • 1970-01-01
            相关资源
            最近更新 更多