Tuesday, April 23, 2013

Create text file, copy text file, move text file and The process cannot access the file because it is being used by another process.


  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string fileName = "test.txt";
            string sourcePath = @"E:\Users\Public\TestFolder";
            string targetPath = @"E:\Users\Public\TestFolder\SubDir";

            // Use Path class to manipulate file and directory paths. 
            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            File.Create(sourcePath + "\\test.txt").Dispose();           
            if (!System.IO.Directory.Exists(targetPath))
            {
                System.IO.Directory.CreateDirectory(targetPath);
            }

            //System.IO.File.Copy(sourceFile, destFile,false);

            if (System.IO.Directory.Exists(sourcePath))
            {
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                // Copy the files and overwrite destination files if they already exist. 
                foreach (string s in files)
                {
                    StreamWriter sw = new StreamWriter(s, true);
                    sw.WriteLine("my sssssdfdf df dfd d fd fdf d 55454545454545");
                    sw.Flush();
                    sw.Close();

                    // Use static Path methods to extract only the file name from the path.
                    fileName = System.IO.Path.GetFileName(s);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(s, destFile, true);
                   // System.IO.File.Move(s, destFile);

                  
                }
               
              
            }
            else
            {
                MessageBox.Show("Source path does not exist!");
            }


            //string pathDirectory = @"E:\\testfolder\\";
            //string pathMoveDirecoty=@"D:\\Receivedtestfiles\\";
            //if (Directory.Exists(pathDirectory))
            //{
            //    string[] allFiles = Directory.GetFiles(pathDirectory);
            //    if (allFiles.Length > 0)
            //    {
            //        Directory.Move(allFiles[0].ToString(), pathMoveDirecoty + allFiles[0].ToString());
            //    }
            //}
        }
    }

No comments:

Post a Comment