如何为文件名添加第二个扩展名?

How to add a second extension to a file name?

我想创建一个数据文件,但在写入最终文件之前,我想将它放在一个临时位置以避免用户混淆。例如,我可以从 test.txt 开始,然后想要 test.txt.tmp。名称可以包含路径,但文件可能不一定存在(所以这个问题纯粹是关于字符串操作)。

我最接近的是使用Path.ChangeExtension:

string original = "test.txt";
string temp = Path.ChangeExtension(original, "tmp");

而是returnstest.tmp。所以我的问题是是否有内置方法来实现 "dual-extension" 文件名?我总是可以使用脑死亡的字符串连接,但我正在寻找一种更安全和经过测试的方法。

为什么你不能像

一样附加那个字符串
if(!string.IsNullOrEmpty(Path.GetExtension(original)){
  original+= ".tmp";
}

如果要使用临时文件,可以使用 Path.GetTempFileName();

string tempFileName = Path.GetTempFileName();

或者您的情况:

 string original = "test.txt";
 string temp = "test.txt" + ".tmp";

您应该使用 temp file 并重命名扩展。

string path = Path.GetTempFileName();
// some logic on the file then rename the file and move it when you need it

string fileName = Path.GetFileName(path);
File.Move(path, path.Replace(fileName, "test.txt"));

避免陷阱对于 Path.Combine 之类的事情来说是个好主意,例如因为您不想被打扰检查是否没有丢失 \ 字符。

但是这里没有陷阱。

  • 如果您的原始文件名与您预期的一样,则字符串连接将起作用。
  • 如果您的原始文件名与您预期的不一样,那么问题出在为您提供错误文件名的人身上。 "Shit goes in, shit comes out" 并不是您的内部逻辑真正应该担心的事情。算法的正确性取决于它接收到的信息。

这里完全可以接受字符串连接。这里没有预制方法,因为简单地连接字符串没有真正的陷阱。


特别感谢 AlessandroD'Andria 的建议:

Path.ChangeExtension(original, Path.GetExtension(original) + ".tmp");

从技术上讲,它采用了 Path 逻辑,因此符合您的标准。我真的很喜欢遵循您的期望的聪明之处。

但是,这样做根本没有任何好处。就其本质而言,扩展被定义为 "the last part of the filename".

是直接进行字符串连接,还是这样做:

  • 将字符串分成两部分(文件名、扩展名)
  • 在最后一段添加一些内容(扩展名 + 临时扩展名)
  • 再次将所有内容粘贴在一起

最终结果总是一样。字符串的截断是不必要的工作。