ali ak
ali ak

Reputation: 19

I cant copy files using FileStream

I am trying to read/write files using FileStream. Code is working but After copied files all I get an empty file. String data inside the file is not copied.

if (openFileDialog1.ShowDialog() == DialogResult.OK) 
{ 
    if(saveFileDialog1.ShowDialog()==DialogResult.OK)
    {
        FileStream streamR = new FileStream(openFileDialog1.FileName, FileMode.Open);
        byte[] buffer = new byte[streamR.Length];
        streamR.Read(buffer, 0, buffer.Length);
        FileStream streamW = new FileStream(saveFileDialog1.FileName,FileMode.Create);
        int read_byte = 0;
        while ((read_byte = streamR.Read(buffer, 0, buffer.Length)) > 0) 
        {
            streamW.Write(buffer, 0, read_byte);
        }
    }
}

Upvotes: 0

Views: 184

Answers (2)

AlexanderBrevig
AlexanderBrevig

Reputation: 1987

I would do something along these lines:

if (openFileDialog1.ShowDialog() == DialogResult.OK 
    && saveFileDialog1.ShowDialog() == DialogResult.OK){
    try {
        if (File.Exists(saveFileDialog1.FileName)) {
            File.Delete(saveFileDialog1.FileName);
        }
        File.Copy(openFileDialog1.FileName, saveFileDialog1.FileName);
    } catch (Exception e){
        //handle or throw e
    }
}

Upvotes: 0

Nullius
Nullius

Reputation: 2702

When using streams, you should use the 'using' command:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{ 
    if(saveFileDialog1.ShowDialog()==DialogResult.OK)
    {
        using (FileStream streamR = new FileStream(openFileDialog1.FileName, FileMode.Open))
        {
            using (FileStream streamW = new FileStream(saveFileDialog1.FileName,FileMode.Create))
            {
                byte[] buffer = new byte[streamR.Length];
                int read_byte = 0;
                while ((read_byte = streamR.Read(buffer, 0, buffer.Length)) > 0)
                {
                    streamW.Write(buffer, 0, read_byte);
                }
            }
        }
    }
}

It will automatically flush, close and dispose the streams for you. What actually stops your code from working, is the flush() and close() command. However, it's still recommended to use the 'using' command.

A second way is to wrap everything in a try finally block and dispose the stream in the finally block: using statement FileStream and / or StreamReader - Visual Studio 2012 Warnings

Anyway, I would suggest reading some more information about streams before continuing. On the other hand ... if it's just for copying files, it would be simpler to use the Fil.Copy method.

Edit: Also ... loading the original file completely into a byte-array can cause some extra problems when your file is quite large. The buffer is there to read chunks from the original file and process them. I just corrected your code to make it work ... but it's far from perfect.

Upvotes: 2

Related Questions