Question

Im trying to send an image to a remote server that I'm taking with my current program. How I've done this is first the image must be saved to the user's Workstation, then I'm storing that location and passing it to my method in order to pass it to my server.

However, when I run the code to pass the image along I get an error saying that my file type is not supported.

Here is a run down of my code:

public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
    {
        Console.Write(string.Format("Uploading {0} to {1}", file, url));
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        Stream rs = wr.GetRequestStream();

        string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        foreach (string key in nvc.Keys)
        {
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        }
        rs.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
        string header = string.Format(headerTemplate, paramName, file, contentType);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        rs.Write(headerbytes, 0, headerbytes.Length);

        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            rs.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();

        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
        rs.Write(trailer, 0, trailer.Length);
        rs.Close();

        WebResponse wresp = null;
        try
        {
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
            Console.Write(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
        }
        catch (Exception ex)
        {
            Console.Write("Error uploading file", ex);
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
        {
            wr = null;
        }
    }

I'm calling the method like so:

  NameValueCollection nvc = new NameValueCollection();
  nvc.Add("id", "TTR");
  nvc.Add("btn-submit-photo", "Upload");
 HttpUploadFile("http://WebSiteLocation.com/images/uploadimage.html", sfd.ToString(),"image", "image/jpeg", nvc);

In the above method sfd relates to the save file dialog I use to save the image. The error is this:

The given path's format is not supported.

Which is highlighted in this line:

 FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);

I thought that the above code would be fine to send any file along which is why I'm confused this is happening.

Can anyone see the reason why? I've spent a while looking at this and I think a fresh pair of eyes and brain are needed.

For the sake of completion the string I get back when I call sfc.ToString() is this:

System.Windows.Forms.SaveFileDialog: Title: FileName: C:\Users\MyComputer\Desktop\Img.png

Was it helpful?

Solution

That exception message isn't complaining about the format of the file. It's complaining about the format of the file name. You probably have invalid characters in the path.

In the code before you try to open the file, write this:

if (file.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
{
    throw new ArgumentException("File name contains invalid characters", "file");
}

If that identifies the problem, then your best bet is to fix that before you call the method. Perhaps you can just strip the offending characters or convert them to underlines. Without knowing more about how your program works, it's tough to make recommendations.

OTHER TIPS

Are you parsing the file name out of that string (sfd)? Without running it locally, my first guess is that the string you're using for the file name is bad. It should only be the path to the file, correct?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top