C# 服務器間讀取上傳圖片實現

由於項目使用了負載,所以有這樣的需求,需要把文件保存到同一個服務器下,然後去指定的服務器讀取文件。

我經過了一些搜索,找到了2個辦法來實現。一種是使用共享文件夾的方式,還有一種是使用FTP協議去傳輸文件。

下面先記錄下使用共享文件夾的方式。

首先,在指定服務器下,創建共享文件,名稱爲Share,把它共享給所有人,讀寫權限。

然後,代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace MB.Cloud.PosService.ServerBiz.Basic.Base
{
    public class ShareFileHelper
    {
        public void Execute()
        {

            bool status = false;

            //連接共享文件夾
            status = connectState(@"\\10.100.20.122\Share", "用戶名", "密碼");
            if (status)
            {
                //共享文件夾的目錄
                DirectoryInfo theFolder = new DirectoryInfo(@"\\10.100.20.122\Share");
                //相對共享文件夾的路徑
                string fielpath = @"\123\456\";
                //獲取保存文件的路徑
                string filename = theFolder.ToString() + fielpath + "1.jpg";
                string filePath = @"C:\Users\hq01ub721\Desktop\臨時\";
                //執行方法
               Transport(filename, filePath, "3.jpg"); //這是從共享文件夾讀取文件到本地
                
           }
            else
            {
                //ListBox1.Items.Add("未能連接!");
            }
            Console.ReadKey();
        }

        public static bool connectState(string path)
        {
            return connectState(path, "", "");
        }
        /// <summary>
        /// 連接遠程共享文件夾
        /// </summary>
        /// <param name="path">遠程共享文件夾的路徑</param>
        /// <param name="userName">用戶名</param>
        /// <param name="passWord">密碼</param>
        /// <returns></returns>
        public static bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

        /// <summary>
        /// 向遠程文件夾保存本地內容,或者從遠程文件夾下載文件到本地
        /// </summary>
        /// <param name="src">要保存的文件的路徑,如果保存文件到共享文件夾,這個路徑就是本地文件路徑如:@"D:\1.avi"</param>
        /// <param name="dst">保存文件的路徑,不含名稱及擴展名</param>
        /// <param name="fileName">保存文件的名稱以及擴展名</param>
        public static void Transport(string src, string dst, string fileName)
        {

            FileStream inFileStream = new FileStream(src, FileMode.Open);
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;
            FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);

            byte[] buf = new byte[inFileStream.Length];

            int byteCount;

            while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
            {

                outFileStream.Write(buf, 0, byteCount);

            }

            inFileStream.Flush();

            inFileStream.Close();

            outFileStream.Flush();

            outFileStream.Close();

        }
    }
}
FTP文件傳輸方式

首先在服務器端建立FTP站點,然後就可以通過代碼,或者瀏覽器訪問了。

代碼如下:

  public class FtpHelper
    {

        private static string FtpAddress = "10.100.20.122:21";
        private static string LocalPath = @"C:\Users\ShareFileDownload";

        public static void DownLoadFile(string filename)
        {
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + FtpAddress + "/" + filename);
            req.Method = WebRequestMethods.Ftp.DownloadFile;
            req.UseBinary = true;
            req.UsePassive = true;
            req.Credentials = new NetworkCredential(@"POSTEST-1203\Administrator", "pos123");
            try
            {
                using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                {
                    string localfile = Path.Combine(LocalPath, filename);
                    FileStream fs = new FileStream(localfile, FileMode.Create, FileAccess.Write);
                    int buffer = 1024;  //1K緩衝   
                    byte[] b = new byte[buffer];
                    int i = 0;
                    Stream stream = res.GetResponseStream();
                    while ((i = stream.Read(b, 0, buffer)) > 0)
                    {
                        fs.Write(b, 0, i);
                    }
                }
                Console.WriteLine(filename + " download!");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {

            }
        }


        /// <summary>   
        /// 獲取FTP文件列表   
        /// </summary>   
        /// <returns></returns>   
        public static List<String> GetFileList()
        {
            List<string> list = new List<string>();
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FtpAddress + ""));
            //req.Credentials = new NetworkCredential(FtpUid, FtpPwd);
            req.Method = WebRequestMethods.Ftp.ListDirectory;
            req.UseBinary = true;
            req.UsePassive = true;
            try
            {
                using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(res.GetResponseStream()))
                    {
                        string s;
                        while ((s = sr.ReadLine()) != null)
                        {

                            list.Add(s);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return list;

        }

        public static void UploadFile(string localFile)
        {
            FileInfo fi = new FileInfo(localFile);
            FileStream fs = fi.OpenRead();
            long length = fs.Length;
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + FtpAddress + "/123/" + fi.Name);
           // req.Credentials = new NetworkCredential(FtpUid, FtpPwd);
            req.Method = WebRequestMethods.Ftp.UploadFile;
            req.UseBinary = true;
            req.ContentLength = length;
            req.Timeout = 10 * 1000;
            try
            {
                Stream stream = req.GetRequestStream();

                int BufferLength = 2048; //2K   
                byte[] b = new byte[BufferLength];
                int i;
                while ((i = fs.Read(b, 0, BufferLength)) > 0)
                {
                    stream.Write(b, 0, i);
                }
                stream.Close();
                stream.Dispose();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

        }

    }
使用以上方式便可以實現文件的傳輸了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章