【问题标题】:Get file extension with a file that has multiple periods使用具有多个句点的文件获取文件扩展名
【发布时间】:2014-02-11 03:24:55
【问题描述】:

C#中获取文件扩展名很简单,

FileInfo file = new FileInfo("c:\\myfile.txt");
MessageBox.Show(file.Extension); // Displays '.txt'

但是我的应用中有多个句点的文件。

FileInfo file = new FileInfo("c:\\scene_a.scene.xml");
MessageBox.Show(file.Extension); // Displays '.xml'

我希望能够提取名称的.scene.xml 部分。

更新
扩展名还应该包括初始的.

如何从FileInfo 获得此信息?

【问题讨论】:

  • 我使用了 Path v FileInfo,因此您不必创建新的 FileInfo 对象。但要得到你要求的确切结果。 :)

标签: c# .net regex file file-extension


【解决方案1】:

您可以使用此正则表达式提取点符号后的所有字符:

\..*

var result = Regex.Match(file.Name, @"\..*").Value;

【讨论】:

  • + 1:我错过了他想要的 .一开始也是。效果很好。
  • 这立即奏效,我也喜欢@daniel-james-bryars 解决方案。谢谢大家:)
【解决方案2】:

.xml 是扩展名,文件名为scene_a.scene

如果要提取scene.xml。你需要自己解析它。

这样的事情可能会做你想做的事(你需要添加更多代码来检查名称中根本没有 . 的情况。):

String filePath = "c:\\scene_a.scene.xml";

            String myIdeaOfAnExtension = String.Join(".", System.IO.Path.GetFileName(filePath)
                .Split('.')
                .Skip(1));

【讨论】:

  • 是的,目前我只是自己解析它。我希望有一个比我的更强大的 .NET API。
  • @IEnumerable - 我认为这是因为(至少在 Windows 中)“.xml”是文件扩展名,“.scene.xml”不是。
  • 是的,但即使是 VisualStudio 也有多个 Periods 来告诉 App 如何查看文件。无论如何,我想一个好的自定义库也可以!
【解决方案3】:

试试,

IO.Path.GetExtension("c:\\scene_a.scene.xml");

参考。 System.IO.Path.GetExtension

如果你想要 .scene.xml 然后试试这个,

 FileInfo file = new FileInfo("E:\\scene_a.scene.xml");
 MessageBox.Show(file.FullName.Substring(file.FullName.IndexOf(".")));

【讨论】:

  • OP 不想获取文件扩展名 IMO。
  • @IEnumerable 要求不同的东西。我同意这是获得延期的好方法 - 但他要求的是别的东西。
  • 但问题标题说需要多个时期的文件扩展名。
  • @JigneshThakker:但问题主体解释说 IEnumerable 将第一个句点之后的所有内容都视为文件扩展名
  • 是的,第一个句点是扩展的一部分。就像 FileInfo.Extention 会返回一样:)
【解决方案4】:

继续抓取扩展,直到不再有:

var extensions = new Stack<string>(); // if you use a list you'll have to reverse it later for FIFO rather than LIFO
string filenameExtension;
while( !string.IsNullOrWhiteSpace(filenameExtension = Path.GetExtension(inputPath)) )
{
    // remember latest extension
    extensions.Push(filenameExtension);
    // remove that extension from consideration
    inputPath = inputPath.Substring(0, inputPath.Length - filenameExtension.Length);
}
filenameExtension = string.Concat(extensions); // already has preceding periods

【讨论】:

    【解决方案5】:

    老了,我知道。除了关于最佳实践的讨论,您可以这样做:添加换行符以提高可读性。

    "." + Path.GetFileNameWithoutExtension(
               Path.GetFileNameWithoutExtension("c:\\scene_a.scene.xml")
          ) 
    + "." +Path.GetExtension("c:\\scene_a.scene.xml")
    

    这是最好的方法吗?我不知道,但我知道它在一行中工作。 :)

    【讨论】:

      猜你喜欢
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      相关资源
      最近更新 更多