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

后端 未结 3 1878
你的背包
你的背包 2021-01-23 04:52
if (File.Exists(@\"C:\\\\Users\" + Environment.UserName + \"\\\\Desktop\\\\test\"))
{                                                                /\\
                         


        
相关标签:
3条回答
  • 2021-01-23 05:32

    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.

    0 讨论(0)
  • 2021-01-23 05:43

    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);
    }
    
    0 讨论(0)
  • 2021-01-23 05:44

    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.

    0 讨论(0)
提交回复
热议问题