简体   繁体   中英

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

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM