HttpWebRequest Issue to remote server

1.1k Views Asked by At

I'm trying to upload files to a remote server (windows server 2008 R2) from my asp.net 1.1 (C#) Windows application (I know.. It's really old, sadly, that's what we have). When I try to upload, it's giving me an error: "The remote server returned an error: (404) Not Found.". Here's the code I'm using: Any ideas?

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
req.Credentials = new NetworkCredential(uName,pwd);
req.Method = "PUT";
req.AllowWriteStreamBuffering = true;

// Retrieve request stream 
Stream reqStream = req.GetRequestStream();

// Open the local file
FileStream rdr = new FileStream(txt_filename.Text, FileMode.Open);

// Allocate byte buffer to hold file contents
byte[] inData = new byte[4096];

// loop through the local file reading each data block
//  and writing to the request stream buffer
int bytesRead = rdr.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
    reqStream.Write(inData, 0, bytesRead);
    bytesRead = rdr.Read(inData, 0, inData.Length);
}

rdr.Close();
reqStream.Close();

req.GetResponse();

The uploadUrl is like this: http://10.x.x.x./FolderName/Filename

1

There are 1 best solutions below

7
mrciga On

Please use "POST" method instead of "PUT" and I guess it will work.

Edit:

Check the code below, it will help you.

 public void UploadFile()
    {
        string fileUrl = @"enter file url here";
        string parameters = @"image=" + Convert.ToBase64String(File.ReadAllBytes(fileUrl));
        WebRequest req = WebRequest.Create(new Uri("location url here"));

        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(parameters);

        try
        {
            req.ContentLength = bytes.Length;
            Stream s = req.GetRequestStream();
            s.Write(bytes, 0, bytes.Length);
            s.Close();
        }
        catch (WebException ex)
        {
            throw ex; //Request exception.
        }

        try
        {
            WebResponse res = req.GetResponse();
            StreamReader sr = new StreamReader(req.GetResponseStream());
        }
        catch (WebException ex)
        {
            throw ex; //Response exception.
        }
    }

Enter fileUrl variable correctly and take care of uri while creating WebRequest instance, write the url of the locating folder.