Gav*_*ler 4 .net c# file-io file
我正在使用C#输出文件,并希望通过添加括号和数字来处理使用相同名称保存的文件:
FooBar.xml
FooBar(1).xml
FooBar(2).xml
...
FooBar(N).xml
Run Code Online (Sandbox Code Playgroud)
在.NET中有一种简单的方法吗?这个(#)结构有一个特殊的名字吗?
Sam*_*ham 18
您只需要手动计算和操作文件名.下面的(伪)代码很脏,但它是基本算法.根据您的需求重新构建它.
var filenameFormat = "FooBar{0}.xml";
var filename = string.Format(filenameFormat, "");
int i = 1;
while(File.Exists(filename))
filename = string.Format(filenameFormat, "(" + (i++) + ")");
return filename;
Run Code Online (Sandbox Code Playgroud)
如果你可以逃脱它,你可以随时以你选择的格式使用DateTime.Now.无论如何,这就是我们为临时文件所做的事情.
最后,我利用接受的答案创建了一个如下所示的扩展方法:
public static string GetNextFilename(this string filename)
{
int i = 1;
string dir = Path.GetDirectoryName(filename);
string file = Path.GetFileNameWithoutExtension(filename) + "{0}";
string extension = Path.GetExtension(filename);
while (File.Exists(filename))
filename = Path.Combine(dir, string.Format(file, "(" + i++ + ")") + extension);
return filename;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4936 次 |
| 最近记录: |