Justin N

Justin N

  • NA
  • 19
  • 0

A very easy answer for a pro, please help.

Jan 5 2010 4:23 AM
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();
        }

Answers (4)