Why does this throw an exception on the second to last line? Im a newbie.
IOException: The process cannot access the file 'F:\Practice\Practice\bin\Debug\mynewfile.txt' because it is being used by another process.
class Program
{
static void Main()
{
// Creates a new textfile titled "mynewfile.txt", copy/clones the file into a new file titled "newfile2.txt"
// and then renames/moves "newfile2.txt" to "newfile3.txt".
File.CreateText("mynewfile.txt");
File.Copy("mynewfile.txt", "newfile2.txt");
File.Move("newfile2.txt", "newfile3.txt");
// Alternatively, you can create an instance of the FileInfo class representing the file and call the Create,
// CreateText, CopyTo, MoveTo and Delete methods. The following code perfoms the same functions as the previous.
FileInfo fi = new FileInfo("myfile.txt");
fi.CreateText();
fi.CopyTo("myfile2.txt");
FileInfo fi2 = new FileInfo("myfile2.txt");
fi2.MoveTo("myfile3.txt");
// Now delete
File.Delete("mynewfile.txt"); // "mynewfile.txt" is being used by another process?????
fi2.Delete();
}
Loading
Nilanka DharmadasaPosted Jan 6, 2010, 12:23 AM
As San K has mentioned, close it before trying to delete. But as he has given File.Close() will not help. You have to close the stream.
Use following code.
// Creates a new textfile titled "mynewfile.txt", copy/clones the file into a new file titled "newfile2.txt"
// and then renames/moves "newfile2.txt" to "newfile3.txt".
StreamWriter f = File.CreateText("mynewfile.txt");
File.Copy("mynewfile.txt", "newfile2.txt");
f.Close();
File.Move("newfile2.txt", "newfile3.txt");
// Alternatively, you can create an instance of the FileInfo class representing the file and call the Create,
// CreateText, CopyTo, MoveTo and Delete methods. The following code perfoms the same functions as the previous.
FileInfo fi = new FileInfo("myfile.txt");
fi.CreateText();
fi.CopyTo("myfile2.txt");
FileInfo fi2 = new FileInfo("myfile2.txt");
fi2.MoveTo("myfile3.txt");
// Now delete
f.Close();
File.Delete("mynewfile.txt"); // "mynewfile.txt" is being used by another process?????
fi2.Delete();
If you find this useful, please tick 'Do you like this answer' checkbox.
Santhosh NPosted Jan 5, 2010, 5:05 AM
Add this line and check..
fi2.MoveTo("myfile3.txt");
File.Close();
// Now delete
File.Delete("mynewfile.txt"); // "mynewfile.txt" is being used by another process?????
fi2.Delete();
Justin NPosted Jan 5, 2010, 4:33 AM
The process cannot access the file 'F:\Practice\Practice\bin\Debug\mynewfile.txt' because it is being used by another process.
kannanPosted Jan 5, 2010, 4:28 AM