C# .NET - moving files from one folder to another

Asked By toink toink
09-Mar-06 03:51 AM
i have these lines of code which transfers files from one folder to another. but an error occurs when the file to transfer is being used by another process... 


[CODE]
private int MoveFiles(String sourcePath, String destinationPath)
		{ 
			int fileCounter = 0; 

			if (destinationPath.LastIndexOf("\\") != destinationPath.Length - 1) 
			{ 
				destinationPath += "\\"; 
			} 

			foreach (string sFile in Directory.GetFiles(sourcePath)) 
			{ 
				string extension = sFile.Substring(sFile.LastIndexOf(".")); 

				if (extension == ".xml" || extension == ".XML") 
				{ 
					if (File.Exists(string.Concat(destinationPath, Path.GetFileName(sFile)))) 
					{ 
						if (MessageBox.Show(String.Format("{0}: already exists. Replace?", string.Concat(destinationPath, Path.GetFileName(sFile))), "TODO", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) 
						{ 
							File.Delete(string.Concat(destinationPath, Path.GetFileName(sFile))); 
							File.Move(sFile, string.Concat(destinationPath, Path.GetFileName(sFile))); 
							++fileCounter; 
						} 
					} 
					else 
					{ 
						File.Move(sFile, string.Concat(destinationPath, Path.GetFileName(sFile))); 
						++fileCounter; 
					} 
				} 
			} 
			return fileCounter; 
		} 

[/CODE]



the error will occur in this line
[CODE]

						File.Move(sFile, string.Concat(destinationPath, Path.GetFileName(sFile))); 
[/CODE]

how will i check if the file is being used by another process before i'll transfer it? thanks

moving files from one folder to another  moving files from one folder to another

09-Mar-06 04:43 AM
You should use Try Catch block to know the problem exactly.

Some times problem occurs when the handle to file is not kept.

By the way insert this code 

[CODE]
using (FileStream fs = File.Create(path)) {}
[/CODE]
just after this line

[CODE]
if (File.Exists(string.Concat(destinationPath, Path.GetFileName(sFile))))      	
{
....
.....
...
[/CODE]
and check whether problem persists.

review  review

09-Mar-06 04:57 AM
the code is quite confusing...
which path am i going to place inside the parentheses? the destination path? or the sourcepath? what is the effect of using these lines?

review  review

09-Mar-06 05:03 AM
place your source path inside the parentheses.

this statement just creates a file stream around the file and closes it explicitely.
Handle System IO IOException Exception  Handle System IO IOException Exception
09-Mar-06 05:34 AM
You will have to make to it read ony before moving the file or 
Handle System.IO.IOException Exception in try catch block and massage to user accordingly .
You can't move file when its open in writable mode.
check  check
09-Mar-06 05:59 AM
i already tried the try catch method.. and it worked fine
but what i really like to do is to check if it is used by another process or not rather than a try catch block.. any other idea? still got a problem with it... thanks
The Only Way  The Only Way
09-Mar-06 10:15 AM
As far as I know, that's the only way for you to determine if the file is being used or not.  In your try/catch block, you can check for the error code or error message and if it says file is being used, then the file is being used.
Checking FIle is used by another process or not  Checking FIle is used by another process or not
08-May-09 03:25 AM
Reference URL:

http://alperguc.blogspot.com/2008/11/c-process-cannot-access-file-because-it.html

Sample Code :

You can check whether a file is being used or not with a simple function.
Try to open a file with none share.
 public bool IsFileUsedbyAnotherProcess(string filename)
{
try
{
File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (System.IO.IOException exp)
{
return true;
}
return false;

}
Create New Account
help
IOException Mobile Apps Hi I have developed an application which always giving IOException when I run it second time. If I shutdown my PDA and on it and Path.DirectorySeparatorChar (1) System.Collections.Generic (1) Path.GetDirectoryName (1) System.Windows.Forms (1) Path.GetFileName (1) Which part is throwning the IOExpection? Could the exception be because a file is DirectoryInfo di = new DirectoryInfo(localPath + " / Content"); if (di.Exists = = false) di.Create(); int pubIndex_zip = pubtitle.LastIndexOf(".zip"); string pubtitle_val = pubtitle.Substring(0, pubIndex_zip); FileStream fs = File.OpenRead(zipPath); try { ZipInputStream zis theEntry; while ((theEntry = zis.GetNextEntry()) ! = null) { string dirName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); string serverFolder = pubsFolder + Path.DirectorySeparatorChar + pubtitle_val; Directory.CreateDirectory(serverFolder + Path.DirectorySeparatorChar + dirName); if throwing the error? - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - = - -- According to the MSDN documentation the File.Delete call will thrown an IOException when "The specified file is in use." Link: http: / / msdn2.microsoft.com / en-us / library void deleteZips( FileInfo[] zips ) { foreach( FileInfo zip in zips ) { try { File.Delete( zip.FullName ); } catch( IOException ex ) { MessageBox.Show( ex.Message + ": " + zip.FullName ); } } } - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - = - -- Also according to the MSDN documentation the Directory.CreateDirectory call should be throwing an IOException when "The directory specified by path is read-only or is not empty. -or- A
DirectoryInfo diSourceDir in source.GetDirectories()) { DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name); CopyAll(diSourceDir, nextTargetDir); } } catch (IOException ie) { } } } } Hi, Here are the steps can follow • Upload a file - .pdf • Save the file you if (addTopFileUpload.HasFile && addBottomFileUpload.HasFile) { try { string filepath = "~ \ Banners \ "; string topbanner = System.IO.Path.GetFileName(addTopFileUpload.FileName); string bottombanner = System.IO.Path.GetFileName(addBottomFileUpload.FileName); string dbtopfilepath = filepath + topbanner; string dbfilebottompath = filepath + bottombanner; string fileTopPathToSave = Server.MapPath(filepath strPath + strFname ; if ( System . IO . File . Exists ( strFname )) { string filename = strFname . ToString (); int intPos = filename . LastIndexOf ( " / " ); string strUploadedFileName = filename . Substring ( intPos + 1 ); Response . ContentType = "APPLICATION / OCTET-STREAM" ; System . String disHeader = "Attachment strPath + strFname ; if ( System . IO . File . Exists ( strFname )) { string filename = strFname . ToString (); int intPos = filename . LastIndexOf ( " / " ); string strUploadedFileName = filename . Substring ( intPos + 1 ); Response . ContentType = "APPLICATION / OCTET-STREAM" ; System . String disHeader = "Attachment