Monday, 14 March 2016

Copy file and delete from Directory(Task Based) in C#

 /// <summary>
        /// To move file source to target and delete from source
        /// </summary>
        /// <returns>bool type may be true or false</returns>
        public async Task<bool> FileDeleteAndCopy()
        {
            try
            {
                string sourcePath = @"G:\New";
                string targetPath = @"G:\Old";
                string sourceFile = System.IO.Path.Combine(sourcePath);
                string destFile = System.IO.Path.Combine(targetPath);

                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                    label1.Text = "Creating directory for target path";
                }

                if (!System.IO.Directory.Exists(sourcePath))
                {
                    System.IO.Directory.CreateDirectory(sourcePath);
                    label1.Text = "Creating directory for source path";
                }

                if (System.IO.Directory.Exists(sourcePath))
                {
                    string[] files = System.IO.Directory.GetFiles(sourcePath);
                    foreach (string filename in files)
                    {
                        string strDatetime = DateTime.Now.ToString("ddMMyyyyHHss");
                        string FileNameArray = System.IO.Path.GetFileName(filename);
                        destFile = System.IO.Path.Combine(targetPath, strDatetime + FileNameArray);
                        System.IO.File.Copy(filename, destFile, false);
                        label1.Text = "Moving file to target folder " + filename.ToString();
                    }
                    //Delete from source folder.
                    string[] fileList = Directory.GetFiles(sourceFile);
                    foreach (var flist in fileList)
                    {
                     
                        await Task.Run(() =>
                        {
                            File.Delete(flist);
                        });
                        label1.Text = " Deleting file from source folder " + flist.ToString();
                    }
                    return true;

                }
                return true;
            }
            catch (Exception ex)
            {
                ErrorLog(ex.Message.ToString());
                return false;
            }

        }

No comments:

Post a Comment