Uploading Files Using .NET

This .NET source code uploads files to the Panel. Change values of the Hostname, Login, Password, and Protocol variables with parameters of the Panel instance. Change value of the Filename variable with full name of the file you want to upload.

 

Filename

Full name of the file to be uploaded.

Hostname

The IP address or name of the Panel-managed server.

Login

Login name of the Panel administrator.

Password

Password of the Panel administrator.

Protocol

Version of the API RPC protocol.

 

using System;
using System.Net;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
 
namespace ConsoleApplication1
{ 
 
 public class Request
 { 
  // Public interface
  // 
  public string Filename = "./tmp/myfile.sh";   // Upload file name;
  public string Hostname = "localhost";	// The Panel's host name
  public string Login = "admin";		// Administrator Login
  public string Password = "setup";		// Administrator Password
  public string Protocol = "1.6.2.0";	// API RPC Version Protocol.  
  // Handler for receiving information about document type definition (DTD),
  // XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) schema validation errors. 
  public ValidationEventHandler XmlSchemaValidation = null;
 
  public Request() 
  { 
  } 
 
  public string AgentEntryPoint { get { return "https://" + Hostname + ":8443/enterprise/control/agent.php"; } } 
 
  public string InputValidationSchema { get { return "https://" + Hostname + ":8443/schemas/rpc/" + Protocol + "/agent_input.xsd"; } } 
  public string OutputValidationSchema { get { return "https://" + Hostname + ":8443/schemas/rpc/" + Protocol + "/agent_output.xsd"; } }
 
  public XmlDocument UploadFile(string uploadfile)
  { 
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AgentEntryPoint); 
 
   string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); 
 
   request.Headers.Add("HTTP_AUTH_LOGIN", Login); 
   request.Headers.Add("HTTP_AUTH_PASSWD", Password); 
   request.ContentType = "multipart/form-data; boundary=" + boundary; 
   request.Method = "POST";
 
   // Build up the post message header
   StringBuilder sb = new StringBuilder();
   sb.Append("--");
   sb.Append(boundary);
   sb.Append("\r\n");
   sb.Append("Content-Disposition: form-data; name=\"");
   sb.Append("sampfile");
   sb.Append("\"; filename=\"");
   sb.Append(Path.GetFileName(uploadfile));
   sb.Append("\"");
   sb.Append("\r\n");
   sb.Append("Content-Type: ");
   sb.Append("application/octet-stream");
   sb.Append("\r\n");
   sb.Append("\r\n");
 
   string postHeader = sb.ToString();
   byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
 
   // Build the trailing boundary string as a byte array
   // ensuring the boundary appears on a line by itself
   byte[] boundaryBytes =
     Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
 
   FileStream fileStream = new FileStream(uploadfile,
          FileMode.Open, FileAccess.Read);
   long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
   request.ContentLength = length;
   Stream stream = request.GetRequestStream();
 
   stream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
   // Write out the file contents
   byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
   int bytesRead = 0;
   while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    stream.Write(buffer, 0, bytesRead);
 
   // Write out the trailing boundary
   stream.Write(boundaryBytes, 0, boundaryBytes.Length); 
 
   XmlDocument result = GetResponse(request);
   return result;
  } 
 
  // Private interface
  //
 
 
  // Parsing and validating packet 
  // 
  private XmlDocument ParseAndValidate(TextReader xml, string schemaUri)
  {
   XmlSchemaSet schemas = new XmlSchemaSet();
   schemas.Add(null, schemaUri);
 
   XmlReaderSettings settings = new XmlReaderSettings();
   if (XmlSchemaValidation != null)
    settings.ValidationEventHandler += new ValidationEventHandler(XmlSchemaValidation);
   settings.ValidationType = ValidationType.Schema;
   settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
   settings.Schemas = schemas;
 
   XmlDocument document = new XmlDocument();
 
   using (XmlReader reader = XmlTextReader.Create(xml, settings))
   {
    document.Load(reader);
   }
 
   return document;
  }
  private XmlDocument GetResponse(HttpWebRequest request)
  {
   using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
   using (Stream stream = response.GetResponseStream())
   using (TextReader reader = new StreamReader(stream))
   {
    return ParseAndValidate(reader, OutputValidationSchema);
   }
  }
 }
 
 class Program
 {
  static void Main(string[] args)
  {
   if (args.Length < 4)
   {
    Console.WriteLine("Usage: Pleskapirpcclient <Hostname> <Login> <Password> <FileName>");
    Console.WriteLine(" ");
    Console.WriteLine(" Hostname - The Panel's host name");
    Console.WriteLine(" Login  - Administrator login");
    Console.WriteLine(" Password - Administrator password");
    Console.WriteLine(" FileName - Upload file name");
    return;
   }
 
   // Verifies the remote Secure Sockets Layer (SSL/TLS) certificate used for authentication.
   ServicePointManager.ServerCertificateValidationCallback =
    new RemoteCertificateValidationCallback(RemoteCertificateValidation);
 
   Request request = new Request();
   request.XmlSchemaValidation = XmlSchemaValidation;
 
   try
   {
    XmlDocument result = request.UploadFile(filename);
 
    PrintResult(result);
   }
   catch (Exception e)
   {
    Console.WriteLine("Request error: {0}", e.Message);
   }
  }
 
  // The following method is invoked by the RemoteCertificateValidationDelegate.
  private static bool RemoteCertificateValidation(object sender,
   X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  {
   if (sslPolicyErrors != SslPolicyErrors.RemoteCertificateNotAvailable)
    return true;
 
   Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
 
   // Do not allow this client to communicate with unauthenticated servers.
   return false;
  }
  // 
  private static void XmlSchemaValidation(object sender, ValidationEventArgs e)
  {
   Console.WriteLine("Validation error: {0}", e.Message);
  }
 
  static void PrintResult(XmlDocument document)
  {
   XmlTextWriter writer = new XmlTextWriter(Console.Out);
   writer.Formatting = Formatting.Indented;
 
   document.WriteTo(writer);
 
   writer.Flush();
   Console.WriteLine();
  }
 }
}
 

Leave your feedback on this topic here

If you have questions or need support, please visit the Plesk forum or contact your hosting provider.
The comments below are for feedback on the documentation only. No timely answers or help will be provided.