How to move a file that has no file extension? C#

2020-04-18 05:51发布

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

标签: c# file io
3条回答
仙女界的扛把子
2楼-- · 2020-04-18 06:10

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.

查看更多
The star\"
3楼-- · 2020-04-18 06:13

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.


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.

查看更多
迷人小祖宗
4楼-- · 2020-04-18 06:23

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().

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#?:

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#:

if(File.Exists(fullPath))
{
    string newPath = fullPath + ".txt";     
    File.Move(fullPath, newPath);
}
查看更多
登录 后发表回答