Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use filestream for copying files in c#

I want to copy a file from one folder to another folder using filestream.How this can be achived.when I try to use file.copy I was getting this file is using by another process, to avoid this I want to use file stream using c#. Can some one provide a sample for copying a file from one folder to another.

like image 543
N.RaviKumar Avatar asked Sep 12 '25 18:09

N.RaviKumar


1 Answers

for copying i used below code :-

 public static void Copy(string inputFilePath, string outputFilePath)
    {
        int bufferSize = 1024 * 1024;

        using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write,FileShare.ReadWrite))
        //using (FileStream fs = File.Open(<file-path>, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            FileStream fs = new FileStream(inputFilePath, FileMode.Open, FileAccess.ReadWrite);
            fileStream.SetLength(fs.Length);
            int bytesRead = -1;
            byte[] bytes = new byte[bufferSize];

            while ((bytesRead = fs.Read(bytes, 0, bufferSize)) > 0)
            {
                fileStream.Write(bytes, 0, bytesRead);
            }
        }
    }
like image 137
N.RaviKumar Avatar answered Sep 14 '25 08:09

N.RaviKumar