How to write contents of one file to another file?

后端 未结 8 1456
遇见更好的自我
遇见更好的自我 2020-12-09 10:46

I need to write contents of a file to another file using File.OpenRead and File.OpenWrite methods. I am unable to figure out how to do it.

How can i modify the follo

相关标签:
8条回答
  • 2020-12-09 11:22

    Try something along these lines:

    using (FileStream input = File.OpenRead(pathToInputFile),
        output = File.OpenWrite(pathToOutputFile))
    {
        int read = -1;
        byte[] buffer = new byte[4096];
        while (read != 0)
        {
            read = input.Read(buffer, 0, buffer.Length);
            output.Write(buffer, 0, read);
        }
    }
    

    Note that this is somewhat 'skeletal' and you should amend as required for your application of it.

    0 讨论(0)
  • 2020-12-09 11:22

    Have you checked that the reader is reading all the data? This MSDN page has an example that checks all the data is read:

        byte[] verifyArray = binReader.ReadBytes(arrayLength);
        if(verifyArray.Length != arrayLength)
        {
            Console.WriteLine("Error reading the data.");
            return;
        }
    

    The other alternative is that you probably need to Flush the output buffer:

    writer.Flush();
    
    0 讨论(0)
  • 2020-12-09 11:24

    You should be using File.Copy unless you want to append to the second file.

    If you want to append you can still use the File class.

    string content = File.ReadAllText("C:\\file1.txt");
    File.AppendAllText("D:\\file2.txt",content);
    
    0 讨论(0)
  • 2020-12-09 11:26

    Is it necessary to us FileStream? Because you can do this very easily with simple File Class like;

    using System.IO;
    string FileContent = File.ReadAllText(FilePathWhoseTextYouWantToCopy);
    File.WriteAllText(FilePathToWhomYouWantToPasteTheText,FileContent);
    
    0 讨论(0)
  • 2020-12-09 11:26
    using (var inputStream = File.OpenRead(@"C:\file1.txt"))
    {
        using (var outputStream = File.OpenWrite(@"D:\file2.txt"))
        {
            int bufferLength = 128;
            byte[] buffer = new byte[bufferLength];
            int bytesRead = 0;
    
            do
            {
                bytesRead = inputStream.Read(buffer, 0, bufferLength);
                outputStream.Write(buffer, 0, bytesRead);
            }
            while (bytesRead != 0);
        }
    }
    
    0 讨论(0)
  • 2020-12-09 11:26

    Use FileStream class, from System.IO.

    [ComVisibleAttribute(true)]
    public class FileStream : Stream
    
    0 讨论(0)
提交回复
热议问题