Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move files in C#

Tags:

I am moving some images (filenames are(1).PNG, (2).PNG and so on) from one directory to another. I am using the following code:

for (int i = 1; i < n; i++) {     try     {         from = "E:\\vid\\(" + i + ").PNG";         to = "E:\\ConvertedFiles\\" + i + ".png";         File.Move(from, to); // Try to move         Console.WriteLine("Moved"); // Success     }     catch (IOException ex)     {         Console.WriteLine(ex); // Write error     } } 

However, I am getting the following error:

A first chance exception of type System.IO.FileNotFoundException occurred in mscorlib.dll

System.IO.FileNotFoundException: Could not find file 'E:\vid\(1).PNG'. 

Also, I am planning to rename the files so that the converted file name will be 00001.png, 00002.png, ... 00101.png and so on.

like image 428
MKS Avatar asked Nov 29 '12 08:11

MKS


People also ask

What is a move file?

The Move File activity moves a file from one directory to another. You can move files to network shares that are available using UNC paths. You can also move files from a local or publicly available network folder, such as an FTP location, to an internal folder.

How do I move a file into a folder in C#?

public static void Move (string sourceDirName, string destDirName); This method takes the source directory/file path and the destination directory/file path as input. It creates a new directory with the destination directory name and moves the source directory (or file) to the destination.

How do I move a file to a different directory?

Select the file you want to move by clicking on it once. Right-click and pick Cut, or press Ctrl + X . Navigate to another folder, where you want to move the file. Click the menu button in the toolbar and pick Paste to finish moving the file, or press Ctrl + V .

What is the command to move a file?

To move files, use the mv command (man mv), which is similar to the cp command, except that with mv the file is physically moved from one place to another, instead of being duplicated, as with cp.


1 Answers

I suggest you to use '@' in order to escape slashes in a more readable way. Use also Path.Combine(...) in order to concatenate paths and PadLeft in order to have your filenames as your specifics.

for (int i = 1; i < n; i++) {     try     {         from = System.IO.Path.Combine(@"E:\vid\","(" + i.ToString() + ").PNG");         to = System.IO.Path.Combine(@"E:\ConvertedFiles\",i.ToString().PadLeft(6,'0') + ".png");          File.Move(from, to); // Try to move         Console.WriteLine("Moved"); // Success     }     catch (IOException ex)     {         Console.WriteLine(ex); // Write error     } } 
like image 88
Tobia Zambon Avatar answered Nov 23 '22 23:11

Tobia Zambon