C#中相当于Python的os.path.splitext()的是什么?

1 投票
1 回答
631 浏览
提问于 2025-04-16 11:39

在Python中,有一个叫做os.path.splitext()的功能,可以用来替换文件的扩展名,像下面这样。

import os.path
names = os.path.splitext('hello.exe')
print names[0] + ".coverage"

我有一个文件叫hello.coverage

那么C#有没有和Python的os.path相似的功能呢?

已回答

using System;
using System.IO;

namespace Hello 
{
    class Code 
    {
        static void Main(string[] args)
        {
            string path = "hello.exe";
            string newPath = Path.ChangeExtension(path, ".coverage");

            Console.WriteLine("{0} - {1}", path, newPath);
        }
    }
}

1 个回答

3

System.IO.Path.ChangeExtension 可以满足你的需求:

string path = "hello.exe";
string newPath = System.IO.Path.ChangeExtension(path, ".coverage");

编辑: 你的使用声明应该是 using System.IO,这样你就可以像你写的那样使用它,或者这样使用:

Path.ChangeExtension(path, newExtension);

另外,Console.WriteLine 不能像你那样使用。不过你可以这样做:

Console.WriteLine("{0} - {1}", path, newPath);

撰写回答