• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5682
  • Last Modified:

how to upload a file to https using C#

I have an MFC program that uploads a file to an https website.  I am writing a windows service in C# that will take over this upload functionality.  I am vaguely familiar with .NET remoting and .NET web services, but I haven't found any examples using https that requires a username and password.

I did not write the MFC program and I won't know anything about the https website for a few more days.  I just need to see a similar example with .NET classes with C#.  I'm just trying to stay ahead of schedule by initially hacking something that works.

I do not know whether to use the WebClient class or the HttpWebRequest class.  If you could explain when to use each one over the other that would be great too.

This is the (incomplete) MFC code that I need to duplicate in C#:

      CInternetSession session("MyCompany MyNet.dll");
      CHttpConnection* pConn = NULL;
      CHttpFile* pFileLogin = NULL;
      CHttpFile* pFileUpload = NULL;
                  
      //This connection will use SSL (port 443)
      INTERNET_PORT iPort = 443;

      pConn = session.GetHttpConnection(m_strUploadDomainName, iPort, NULL, NULL );

      pFileLogin = pConn->OpenRequest( CHttpConnection::HTTP_VERB_POST, m_strLoginObject,
                        NULL, 1, NULL, NULL, INTERNET_FLAG_SECURE );
                        
      CString strHeader = _T("Content-Type: application/x-www-form-urlencoded");

      CString strData = _T("username=" + m_strHTTPSUserName + "&password=" + m_strHTTPSPassword );

      //Send the login request
      bSuccess = pFileLogin->SendRequest( strHeader, (LPVOID)(LPCTSTR)strData, strData.GetLength() );

      //Get the response
      CString strHeaderResponse, strResponse;
      BOOL bSuccess = TRUE;

      bSuccess = pFileLogin->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF, strResponse );

      //Now create and send the request for the file
      //Open the request...we want to post this one to the upload object
      pFileUpload = pConn->OpenRequest( CHttpConnection::HTTP_VERB_POST, m_strUploadObject,
                              NULL, 1, NULL, NULL );

      strHeader = _T("Content-Type: multipart/form-data");
      strHeader = _T("Content-Type: text/*" );
      bSuccess = pFileUpload->SendRequest( strHeader, pszData, iPostLength );

      //Get the response
      pFileUpload->QueryInfo( HTTP_QUERY_RAW_HEADERS_CRLF, strResponse);



0
big_lew
Asked:
big_lew
2 Solutions
 
SilentBob42Commented:
You can use the WebClient class in the .NET framework.
On MSDN it says it supports https connections:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemnetwebclientclasstopic.asp


So this would translate to:


using System.Net;

WebClient  client = new WebClient();
client.UploadFile("https://www.averysavewebsite.com/Files/sensitivedata.doc", "c:\\websitefiles\\sensitivedata.doc");
0
 
sun4sundayCommented:
0
 
SilentBob42Commented:
sun4sunday, thats uploading for browser-to-server. We're looking for an answer for a windows service as a client.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
big_lewAuthor Commented:
I had read the MSDN documentation on WebClient and HttpWebRequest already, but I could not find an example of how to Login with a username and password like the MFC code does:

     CString strHeader = _T("Content-Type: application/x-www-form-urlencoded");

     CString strData = _T("username=" + m_strHTTPSUserName + "&password=" + m_strHTTPSPassword );

     //Send the login request
     bSuccess = pFileLogin->SendRequest( strHeader, (LPVOID)(LPCTSTR)strData, strData.GetLength() );

MSDN provides an example of how to include a header, but I am still not clear about the login.  Also, if you could explain when to use a WebRequest rather than HttpWebRequest, that would be helpful.

Thanks!
0
 
Bob LearnedCommented:
If you are trying to access intranet resources, and you are logged in, then you just need to pass your credentials (borrowing code from SilentBob42):

WebClient  client = new WebClient();

// Use the credentials from the current logged-in user.
client.Credentials = CredentialCache.DefaultCredentials;

client.UploadFile("https://www.averysavewebsite.com/Files/sensitivedata.doc", "c:\\websitefiles\\sensitivedata.doc");

Bob
0
 
big_lewAuthor Commented:
To reiterate, I have a windows service written in C# that needs to login to an ASP page (not ASP.NET) and provide a username and password to login.  Once I recieve a response that I have successfully logged in, then I can upload the file.  The user name and password required for the ASP login is stored in a .enc file on the local computer.

If I use the following code:

// Use the credentials from the current logged-in user.
client.Credentials = CredentialCache.DefaultCredentials;

Where do the DefaultCredentials come from?  When you say logged in, are you talking about being logged in to the local computer or being logged in to the secure ASP?  The username and password for the local computer is different than what is needed for the ASP login.

0
 
big_lewAuthor Commented:
I cannot use the Credentials property because the Add method of the CredentialCache class adds an instance of the NetworkCredential class.  The NetworkCredential class does not support public key-based authentication methods such as SSL client authentication.

I am using SSL authentication to provide a username and password to the ASP.  Once I get a successful response from the ASP, I can upload the file.  

I need to know how to submit a username and password (SSL) using https.
0
 
big_lewAuthor Commented:
Ended up using HttpWebRequest to login to the asp:

////////////////////My Code///////////////////////////////////////////////
string uploadData = "username=me&password=mypw";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] uploadByte = encoding.GetBytes(uploadData);

// Create the HttpWebRequest and set its properties
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://myCompany.com/AutoLogin.asp");
request.ContentLength = uploadData.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Timeout = 20000;

// Get a Stream from the HttpWebRequest and write login info to it
Stream uploadStream = request.GetRequestStream();
uploadStream.Write(uploadByte, 0, uploadByte.Length);

/////////////////////////////////////////////////////////////////////////////

Uploading a file is similar except I used request.ContentType = "multipart/form-data"

I will give points to SilentBob42 and TheLearnedOne because I was not clear in my question that I was using SSL and the title of my question should have been "How to post login and upload a file with ssl".  I will try to be more clear next time.

Thanks
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now