How to write contents of one file to another file?

后端 未结 8 1457
遇见更好的自我
遇见更好的自我 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:34

    If you are not keen at using Read/Write function of File , you can better try using Copy functionality

    Easiest will be : 
    
          File.Copy(source_file_name, destination_file_name, true)
    

    true--> for overwriting existing file,without "true" it will create a new file.But if the file already exists it will throw exception without "true" argument.

    0 讨论(0)
  • 2020-12-09 11:39
        using (FileStream stream = File.OpenRead("C:\\file1.txt"))
        using (FileStream writeStream = File.OpenWrite("D:\\file2.txt"))
        {
            BinaryReader reader = new BinaryReader(stream);
            BinaryWriter writer = new BinaryWriter(writeStream);
    
            // create a buffer to hold the bytes 
            byte[] buffer = new Byte[1024];
            int bytesRead;
    
            // while the read method returns bytes
            // keep writing them to the output stream
            while ((bytesRead =
                    stream.Read(buffer, 0, 1024)) > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
            }
        }
    

    Just wonder why not to use this:

    File.Copy("C:\\file1.txt", "D:\\file2.txt");
    
    0 讨论(0)
提交回复
热议问题