C# 如何使用filestream在c中复制文件

C# 如何使用filestream在c中复制文件,c#,.net,filestream,C#,.net,Filestream,我想使用filestream将一个文件从一个文件夹复制到另一个文件夹。如何实现这一点。当我尝试使用file.copy时,另一个进程正在使用此文件,为了避免这种情况,我想使用c使用file stream。有些人可以提供一个示例,用于将文件从一个文件夹复制到另一个文件夹。用于复制,我使用了以下代码:- string fileName = "Mytest.txt"; string sourcePath = @"C:\MyTestPath"; string targetPath

我想使用filestream将一个文件从一个文件夹复制到另一个文件夹。如何实现这一点。当我尝试使用file.copy时,另一个进程正在使用此文件,为了避免这种情况,我想使用c使用file stream。有些人可以提供一个示例,用于将文件从一个文件夹复制到另一个文件夹。

用于复制,我使用了以下代码:-

    string fileName = "Mytest.txt";
    string sourcePath = @"C:\MyTestPath";
    string targetPath =  @"C:\MyTestTarget";
    string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
    string destFile = System.IO.Path.Combine(targetPath, fileName);

    {
        System.IO.Directory.CreateDirectory(targetPath);
    }

    // To copy a file to another location and 
    // overwrite the destination file if it already exists.
    System.IO.File.Copy(sourceFile, destFile, true);
 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);
            }
        }
    }

对于复制,我使用以下代码:-

 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);
            }
        }
    }

可能重复的可能重复的请查看此链接,您可能需要返回,并找出此文件被另一个进程错误使用的原因,而不是在问题上抛出另一个解决方案。可能重复的可能重复的请查看此链接您可能首先需要返回并找出此文件被另一个进程错误使用的原因,而不是在问题上抛出另一个解决方案。这不使用流,按要求。这不按要求使用流媒体。它工作正常,但在之后,您必须添加fs.close;否则,源文件是lockedIt,工作正常,但之后,您必须添加fs.close;否则,源文件将被锁定