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, "", "");
        }
        /// 
        /// 连接远程共享文件夹
        /// 
        /// 远程共享文件夹的路径
        /// 用户名
        /// 密码
        /// 
        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;
        }

        /// 
        /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
        /// 
        /// 要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"
        /// 保存文件的路径,不含名称及扩展名
        /// 保存文件的名称以及扩展名
        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
            {

            }
        }


        ///    
        /// 获取FTP文件列表   
        ///    
        ///    
        public static List GetFileList()
        {
            List list = new List();
            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());
            }

        }

    }
使用以上方式便可以实现文件的传输了。

你可能感兴趣的:(系统开发)