使用具有多个句点的文件获取文件扩展名

时间:2014-02-11 03:24:55

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

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获取此内容?

5 个答案:

答案 0 :(得分:6)

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

\..*

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

答案 1 :(得分:1)

尝试,

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(".")));

答案 2 :(得分:1)

.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));

答案 3 :(得分:0)

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

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

这是最好的方式吗?我不知道,但我确实知道它可以在一条线上工作。 :) enter image description here

答案 4 :(得分:0)

继续抓住扩展程序,直到不再存在:

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