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

kannan46 reputationPosted Jan 4, 2010, 11:28 PM EST
Justin N18 reputationPosted Jan 4, 2010, 11:33 PM EST
The process cannot access the file 'F:\Practice\Practice\bin\Debug\mynewfile.txt' because it is being used by another process.
Santhosh NRank #4,788 · 325 reputationPosted Jan 5, 2010, 12:05 AM EST
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();
Nilanka DharmadasaRank #1,875 · 794 reputationPosted Jan 5, 2010, 7:23 PM EST
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.