c# - 在文件扩展名 C# 之前将字符串插入到文件路径字符串中

标签 c#

我有一个定义文件路径的字符串:

string duplicateFilePath = D:\User\Documents\processed\duplicate_files\file1.jpg;

我打算将文件移动到此位置,但有时同名文件已准备就绪。在这种情况下,我想区分文件名。我有每个可用文件的 crc 值,所以我认为这可能有助于确保单个文件名。我可以创建:

string duplicateFilePathWithCrc = duplicateFilePath + "(" + crcValue + ")";

但这给出了:

D:\User\Documents\processed\duplicate_files\file1.jpg(crcvalue);

我需要:

D:\User\Documents\processed\duplicate_files\file1(crcvalue).jpg;

我怎样才能将 crc 值放入文件扩展名之前的字符串中,同时记住文件路径中可能有其他 .'s 并且文件扩展名会有所不同?

最佳答案

使用 System.IO.Path 中的静态方法类拆分文件名并在扩展名前添加后缀。

string AddSuffix(string filename, string suffix)
{
    string fDir = Path.GetDirectoryName(filename);
    string fName = Path.GetFileNameWithoutExtension(filename);
    string fExt = Path.GetExtension(filename);
    return Path.Combine(fDir, String.Concat(fName, suffix, fExt));
}

string newFilename = AddSuffix(filename, String.Format("({0})", crcValue));

关于c# - 在文件扩展名 C# 之前将字符串插入到文件路径字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24367571/

相关文章:

c# - ASP.NET MVC 路由不工作

c# - 当前的 SynchronizationContext 不能用作 TaskScheduler

c# - 构造函数中的依赖属性、更改通知和设置值

c# - Netsuite:如何将采购订单链接到销售订单

c# - JIT .Net 编译器错误?

c# - 从未同步的代码块调用了对象同步方法。 Mutex.Release() 异常

c# - 使用正则表达式替换坏词

c# - system.windows.forms.sendkeys.sendwait 在窗口最大化时不起作用

c# - 当我创建一个自动属性时,后台会发生什么?

c# - 外键导航属性命名约定替代方案