[英]How to move a file that has no file extension? C#
if (File.Exists(@"C:\\Users" + Environment.UserName + "\\Desktop\\test"))
{ /\
this file has no file extension
}
The file test
has no extension and I need help to either move or rename this file to something with a extension 文件
test
没有扩展名,我需要帮助将此文件移动或重命名为具有扩展名的文件
Having no extension has no bearing on the function. 没有扩展与功能无关。 Also, a rename is really just a move "in disguise", so what you want to do is
此外,重命名实际上只是“伪装”的举动,所以你想要做的是
File.Move(@"C:\Users\Username\Desktop\test", @"C:\Users\Username\Desktop\potato.txt")
Please bear in mind the @ before the string, as you haven't escaped the backslashes. 请记住字符串前面的@,因为你还没有逃过反斜杠。
There's nothing special about extensionless files. 无扩展文件没有什么特别之处。 Your code is broken because you use string concatenation to build a path and you're mixing verbatim and regular string literal syntax.
您的代码被破坏是因为您使用字符串连接来构建路径,并且您正在混合逐字和常规字符串文字语法。 Use the proper framework method for this:
Path.Combine()
. 使用适当的框架方法:
Path.Combine()
。
string fullPath = Path.Combine(@"C:\Users", Environment.UserName, @"Desktop\test");
if(File.Exists(fullPath))
{
}
You also should use the proper framework method to get the desktop path for the current user, see How to get a path to the desktop for current user in C#? 您还应该使用适当的框架方法来获取当前用户的桌面路径,请参阅如何在C#中为当前用户获取桌面路径? :
:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fullPath = Path.Combine(desktopPath, "test");
Then you can call File.Move()
to rename the file, see Rename a file in C# : 然后,您可以调用
File.Move()
来重命名该文件,请参阅使用C#重命名文件 :
if(File.Exists(fullPath))
{
string newPath = fullPath + ".txt";
File.Move(fullPath, newPath);
}
You can get all files without extension in this way: 您可以通过这种方式获取没有扩展名的所有文件:
var files = Directory.EnumerateFiles(@"C:\Users\Username\Desktop\")
.Where(fn => string.IsNullOrEmpty(Path.GetExtension(fn)));
Now you can loop them and change the extension: 现在您可以循环它们并更改扩展名:
foreach (string filePath in filPaths)
{
string fileWithNewExtension = Path.ChangeExtension(filePath, ".txt");
string newPath = Path.Combine(Path.GetDirectoryName(filePath), fileWithNewExtension);
File.Move(filePath, newPath);
}
As you can see, the Path
-class is a great help. 如您所见,
Path
-class是一个很好的帮助。
Update : if you just want to change the extension of a single file that you already know it seems that Dasanko has already given the answer. 更新 :如果您只想更改已经知道的单个文件的扩展名,那么Dasanko似乎已经给出了答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.