shami sheikh
shami sheikh

Reputation: 562

Save file in a folder on another server location with the purely written code on website

I am using mvc I am trying to save a file on another folder i.e on another server. But earlier i was using an approach of creating two different solution and was saving the file using web request. i was sending the request from one solution and was geeting it on another solution. here is my code

         byte[] bytes;
         var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
          /*Creating the WebRequest object using the URL of SaveFile.aspx.*/
            System.Net.HttpWebRequest webRequest =
            (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create
            ("http://localhost:13492/Home/SaveImage");
            webRequest.Method = "POST";
            webRequest.KeepAlive = false;
            /*Assigning the content type from the FileUpload control.*/
            webRequest.ContentType = pic.ContentType ;
            /*Creating the Header object.*/
            System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
            headers.Add("FileName", pic.FileName);
            /*Adding the header to the WebRequest object.*/
            webRequest.Headers = headers;
            /* Convert File Into byte array */
            using (var stream = new MemoryStream())
            {
                pic.InputStream.CopyTo(stream);
                bytes = stream.ToArray();
            }
            /*Getting the request stream by making use of the GetRequestStream method of WebRequest object.*/
            using (System.IO.Stream stream = webRequest.GetRequestStream())//Filling request stream with image stream. 
            {
                /*Writing the FileUpload content to the request stream.*/
                stream.Write(bytes, 0, pic.ContentLength);
            }
            /*Creating a WebResponse object by calling the GetResponse method of WebRequest object.*/
            using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())
            {
                /*Retrieving the response stream from the WebResponse object by calling the GetResponseStream method.*/
                using (System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()))
                {
                    string path = sr.ReadToEnd();
                }
            }

then in another solution i was getting it to save the file.

  public void SaveImage()
    {
        try
        {
            /*Retrieving the file name from the headers in the request. */
            string destinationFileName = Path.Combine(@"~/" + "Portfolio" + "/", Request.Headers["FileName"].ToString());
            string fileName = System.Web.HttpContext.Current.Server.MapPath(destinationFileName);
            //string path = System.IO.Path.Combine(Server.MapPath("."), Request.Headers["FileName"].ToString());
            using (System.IO.FileStream fileStream = System.IO.File.Create(fileName))
            {
                /*Getting stream from the Request object.*/
                using (System.IO.Stream stream = Request.InputStream)
                {
                    int byteStreamLength = (int)stream.Length;
                    byte[] byteStream = new byte[byteStreamLength];
                    /*Reading the stream to a byte array.*/
                    stream.Read(byteStream, 0, byteStreamLength);
                    /*Writing the byte array to the harddisk.*/
                    fileStream.Write(byteStream, 0, byteStreamLength);
                }
            }
            Response.Clear();
            /*Writing the status to the response.*/
            Response.Write(fileName);
        }
        catch (Exception ex)
        {
            /*Writing the error message to the response stream.*/
            Response.Clear();
            Response.Write("Error: " + ex.Message);
        }
    }

So what should i change in code so that i could save the file on another location on another server without writing the code on two different place.

Upvotes: 0

Views: 4460

Answers (2)

shami sheikh
shami sheikh

Reputation: 562

I've got a solution for this problem and its working fine.

 public static void UploadFtpFile(string folderName, string fileName)
    {

        FtpWebRequest request;
        try
        {
            //string folderName;
            //string fileName;
            string absoluteFileName = Path.GetFileName(fileName);

            request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/{2}", "ftp.site4now.net", folderName, absoluteFileName))) as FtpWebRequest;
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UseBinary = true;
            request.UsePassive = true;
            request.KeepAlive = true;
            request.Credentials = new NetworkCredential("Username", "Password");
            request.ConnectionGroupName = "group";

            using (FileStream fs = System.IO.File.OpenRead(fileName))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(buffer, 0, buffer.Length);
                requestStream.Flush();
                requestStream.Close();
            }
        }
        catch (Exception ex)
        {

        }
    }

Upvotes: 1

Sandip
Sandip

Reputation: 262

Follow Below Sample

This sample is for creating a folder on another server over FTP protocol. Please extend it as per need.

using System;
using System.Net;

class Test
{
    static void Main()
    {
        WebRequest request = WebRequest.Create("ftp://host.com/directory");
        request.Method = WebRequestMethods.Ftp.MakeDirectory;
        request.Credentials = new NetworkCredential("user", "pass");
        using (var resp = (FtpWebResponse) request.GetResponse())
        {
            Console.WriteLine(resp.StatusCode);
        }
    }
}

As per the comment by @ADyson you must enable the FTP Protocol before working using this sample

Upvotes: 0

Related Questions