RestSharp for desktop application

Viewed 25

I am using C# desktop application. I have a button that I want to press to upload a pdf or jpg file to my own site server folder location. The below is my trial tests but all failed to upload to the web server. Note I have poor knowledge about dealing with web application or servers.

public static void UploadToCloud(RestClient ocClient, String fileName, String serverPath/*string fileName, string ocLocal*/)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            string localFile = GetFullPath(serverPath, fileName);

            if (File.Exists(localFile) == true)
            {
                Console.WriteLine("local file exits on pc. \n");
                RestRequest requestUpLoad = new RestRequest("/", Method.Post);
                requestUpLoad.AddHeader("Content-Type", "application/octet-stream");

                byte[] dataToUpload = File.ReadAllBytes(localFile);
                requestUpLoad.AddFile("download", dataToUpload, "download.jpg");
                Console.WriteLine("Size of file to upload: " + dataToUpload.Length.ToString() + "\n");
                RestResponse cloudResponse = ocClient.Execute(requestUpLoad);
                Console.WriteLine("Resp: " + cloudResponse.ContentType + "\n");
                Console.WriteLine("Content: " + cloudResponse.Content + "\n");
                Console.WriteLine("Upload has been finished. \n");

            }
            else
            {
                Console.WriteLine("\n" + fileName + " is not found on pc. \n");
            }
        }
1 Answers
Please check below code and manage as per your need


string strFileName;
string strFilePath;
string strFolder;
strFolder = Server.MapPath("./");
// Retrieve the name of the file that is posted.
strFileName = oFile.PostedFile.FileName;
strFileName = Path.GetFileName(strFileName);
if(oFile.Value != "")
{
    // Create the folder if it does not exist.
    if(!Directory.Exists(strFolder))
    {
        Directory.CreateDirectory(strFolder);
    }
    // Save the uploaded file to the server.
    strFilePath = strFolder + strFileName;
    if(File.Exists(strFilePath))
    {
        Console.WriteLine( strFileName + " already exists on the server!");
    }
    else
    {
        oFile.PostedFile.SaveAs(strFilePath);
       Console.WriteLine(strFileName + " has been successfully uploaded.");
    }
}
else
{
    Console.WriteLine("Click 'Browse' to select the file to upload.");
}
Related