Frage

For example, something like this fails:

string oldfile = (@"C:\oldfile.txt");
string newfile = (@"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile, newfile);

Program crashes with "The given path's format is not supported."

EDIT: I'm doing this in a Windows Forms project vs. Console project, does that make a difference? Intuitively I wouldn't think it should, but you never know...

War es hilfreich?

Lösung

The problem is the mixture of the verbatim string format ( @"..." ) and escaping slashes ( "\" )

The second piece of code

string oldFile = @"C:\\oldfile.txt"

creates a path of 'C:\\oldfile.txt' which is not recognised as a valid path.

Either use the first version you gave

string oldFile = @"C:\oldfile.txt"

or

string oldFile = "C:\\oldfile.txt"

Andere Tipps

string oldfile = (@"C:\oldfile.txt");
string newfile = (@"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile , newfile );

or string oldfile = ("C:\oldfile.txt"); string newfile = (@"C:\newfolder\newfile.txt"); System.IO.File.Move(oldfile , newfile );

if the direcotry not exist, create it with Directory.CreateDirectory

In a string literal prefixed with @ the escape sequences starting with \ are disabled. This is convenient for filepaths since \ is the path separator and you don't want it to start an escape sequence.

You simply have to use the below one:

string oldfile = ("C:\\oldfile.txt");
string newfile = ("C:\\newfolder\\newfile.txt");
System.IO.File.Move(oldfile, newfile);

OR

string oldfile = (@"C:\oldfile.txt");
string newfile = (@"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile, newfile);

It works without crash.

Refer this MSDN Article
MSDN says to use like this

 string path = @"C:\oldfile.txt";
 string path2 = @"C:\newfolder\newfile.txt";


if (!File.Exists(path)) 
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top