views:

62

answers:

1

Hi all,

i have problem in sending zip file in network.. all other formats i am able to send except .zip..

i tried a lot i dont no how to do this.. the code i have written at client side to upload file, this is suggested by microsoft here is the link

i am able to create zip file, if i try to open it says corrupted..size of the file also varying lot.

here is code

  public void UploadFile(string localFile, string uploadUrl)
    {

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);

        req.Method = "PUT";
        req.AllowWriteStreamBuffering = true;

        // Retrieve request stream and wrap in StreamWriter
        Stream reqStream = req.GetRequestStream();
        StreamWriter wrtr = new StreamWriter(reqStream);

        // Open the local file


        Stream Stream = File.Open(localFile, FileMode.Open);

        // loop through the local file reading each line 
        //  and writing to the request stream buffer 

        byte[] buff = new byte[1024];
        int bytesRead;
        while ((bytesRead = Stream.Read(buff, 0,1024)) > 0)
        {
            wrtr.Write(buff);
        }



        Stream.Close();
        wrtr.Close();

        try
        {
            req.GetResponse();
        }
        catch(Exception ee)
        {

        }

        reqStream.Close();

please help me...

Thanks

+1  A: 

The main problem is that you're using a StreamWriter, which is a TextWriter, designed for text data, not binary files like zip files.

Additionally there's the problem Jacob mentioned, and also the fact that you're not closing the request stream until after you've received the response - although that won't make any difference because the StreamWriter will close it first.

Here's the fixed code, changed to use using statements (to avoid leaving streams open), a simpler call to the File class, and more meaningful names (IMO).

using (Stream output = req.GetRequestStream())
using (Stream input = File.OpenRead(localFile))
{
    // loop through the local file reading each line 
    //  and writing to the request stream buffer 

    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, 1024)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}

Note that you can easily extract the while loop into a helper method:

public static void CopyStream(Stream input, Stream output)
{
    // loop through the local file reading each line 
    //  and writing to the request stream buffer 

    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = input.Read(buffer, 0, 1024)) > 0)
    {
        output.Write(buffer, 0, bytesRead);
    }
}

to be used from other places, leaving just:

using (Stream output = req.GetRequestStream())
using (Stream input = File.OpenRead(localFile))
{
    CopyStream(input, output);
}
Jon Skeet
Yes.. You are right...Thank you Very much Thanks lot man..
Shadow