Вопрос

Guys I am trying to remane a file (adding _DONE to its name)

my researches showed that File.move(OLDNAME,NEWNAME) is what I needed. Thus, I did,

try
{
    string oldname = name;
    //XYZ_ZXX_ZZZ
    string newName = ToBeTested + "_DONE.wav";
    //rename file
    //NOTE : OldName is already in format XYZ_III_SSS.wav
    File.Move(oldname, newName);

}
catch (Exception exRename)
{
    string ex1 = exRename.ToString();
    //logging an error 
    string m = "File renaming process failed.[" + ex1 + "]";
    CreateLogFile(p, m);
}

But It does not bears any result (File is not renamed) but the exception is logged.

as such

System.IO.FileNotFoundException: Could not find file 'C:\Users\Yachna\documents\visual studio 2010\Projects\FolderMonitoringService_RCCM\FolderMonitoringService_RCCM\bin\Debug\54447874_59862356_10292013_153921_555_877_400_101.wav'.
File name: 'C:\Users\Yachna\documents\visual studio 2010\Projects\FolderMonitoringService_RCCM\FolderMonitoringService_RCCM\bin\Debug\54447874_59862356_10292013_153921_555_877_400_101.wav'
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Move(String sourceFileName, String destFileName)
   at RCCMFolderMonitor.Monitor.OnChanged(Object source, FileSystemEventArgs e) in C:\Users\Yachna\documents\visual studio 2010\Projects\FolderMonitoringService_RCCM\RCCMFolderMonitor\Monitor.cs:line 209]

What did i do wrong ?

Это было полезно?

Решение

I guess that the file does not exist in the same folder as the application.

You will have to include the path in addition to the filename.

File.Move(path + oldname, path + newName);

Другие советы

From the StackTrace it seems that you are trying to move/rename the file whilst you receive the OnChanged event of a FileSystemWatcher component. If this is true this means that another application is writing/changing the file that you are trying to move/rename.
This could result in the above error message. The file exists, but you cannot get access to it until the other application closes it.

Without including the path of your file, Visual Studio looks for the file in your Debug directory. This is the reason of the error.

You have to include the full path of your file using the method Path.Combine of System.IO namespace:

string myDirectory = @"C:\Files";

string myFileName = "myFile.wav";
string myNewFileName = "myFileNew.wav";

string myFileFullPath = Path.Combine(myDirectory, myFileName); 
string myNewFileFullPath = Path.Combine(myDirectory, myNewFileName); 

Console.WriteLine(myFileFullPath); // it writes to Console: C:\Files\myFile.wav

//Then you can rename the file
File.Move(myFileFullPath, myNewFileFullPath);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top