locked
how can i simulate a web xml upload in c# windows application? RRS feed

  • Question

  • I'm working on a c# application that should do exactly the same as the web form below.

    <html>
        <header>
            <title>XML import</title>
        </header>
        <body>
            <form method="post" enctype="multipart/form-data" action="import">
                File to upload: <input type="file" name="upfile"><br>
                <br>
                <input type="submit" value="Upload">
            </form>
        </body>
    </html>

    I tried with this code:

    //Serialiser objektet  
                XmlSerializer ser = new XmlSerializer(typeof(arxdata));  
                TextWriter writer = new StreamWriter(@"c:\arx\ser.xml");  
                try 
                {  
                    ser.Serialize(writer, ad);  
                }  
                catch (Exception ex)  
                {  
                    throw ex;  
                }  
                writer.Close();  
     
                Encoding encoding = Encoding.UTF8;  
     
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url.ToString());  
                req.Credentials = new NetworkCredential(brukernavn, passord);  
                req.Method = "POST";  
                req.ContentType = "multipart/form-data; boundary=B0unD-Ary";  
     
                Stream reqStream = req.GetRequestStream();  
     
                string path = @"c:\arx\ser.xml";  
                StreamWriter swriter = new StreamWriter(reqStream);  
                swriter.WriteLine("--B0unD-Ary");  
                swriter.WriteLine("Content-Disposition: form-data; name=\"upfile\"; filename=\"" + path + "\"");  
     
                swriter.WriteLine("Content-Type: application/binary");  
                swriter.WriteLine("Content-Transfer-Encoding: binary");  
                swriter.WriteLine(); // blank line denotes the end of the headers  
                swriter.Flush();  
                // substitute the code above that copies the file contents out to the response stream  
                swriter.WriteLine(); // the boundary is preceeded by a CR-LF  
                swriter.WriteLine("--B0unD-Ary--");  
                  
                swriter.Flush();  
     
                  
                //Send fil  
                FileStream fs = new FileStream(path,FileMode.Open );     
                // Create a byte array of file stream length     
                byte[] file = new byte[fs.Length];  
                //Read block of bytes from stream into the byte array     
                fs.Read(file,0,System.Convert.ToInt32(fs.Length));     
                //Close the File Stream     
                fs.Close();  
     
                reqStream.Write(file, 0, file.Length);  
     
                reqStream.Close(); 

    Can anyone give me a hint on whats wrong here? Thanks!
    Thursday, October 9, 2008 10:20 AM

Answers

All replies