How to rename a file in C#? Simple and reliable way
Hi everyone! I'm a beginner in C# and writing a small program for working with text files. I need to rename a file after I process it. I tried using File.Move, but something went wrong.\n\nHere's my code:\n\n```csharp\nstring oldPath = @"C:\\temp\\old_file.txt";\nstring newPath = @"C:\\tempew_file.txt";\nFile.Move(oldPath, newPath);\n```\n\nBut I get an exception if the file already exists. How to properly rename a file in C# to avoid such errors? Do I need to check if the file exists, or is there a simpler way?\n\nAlso, I'd like to understand how this works with different extensions (for example, renaming .txt to .csv) and how to handle cases when the file is locked by another process. Thanks in advance for your help!
<<>>
Main method: File.Move
No answers yet.
Log in to leave an answer