编程语言
首页 > 编程语言> > C# 保存WINFORM窗体截图到本地和FTP

C# 保存WINFORM窗体截图到本地和FTP

作者:互联网

代码如下:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsCaptureTest
{
    class SaveFurnacePic
    {

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="form">窗体</param>
        /// <param name="furnaceName">将这个参数附加到生成的文件名中,不是必要的</param>
        public void save(Form form, string furnaceName) 
        {
            try
            {
                //  获取配置的属性
                string ftp_url = System.Configuration.ConfigurationManager.AppSettings["FTP_URL"];
                string ftp_username = System.Configuration.ConfigurationManager.AppSettings["FTP_USERNAME"];
                string ftp_password = System.Configuration.ConfigurationManager.AppSettings["FTP_PASSWORD"];
                string ftp_dir = System.Configuration.ConfigurationManager.AppSettings["FTP_DIR"];
                string local_dir = System.Configuration.ConfigurationManager.AppSettings["LOCAL_DIR"];

                Bitmap bit = new Bitmap(form.Width, form.Height);   // 实例化一个和窗体一样大的bitmap
                Graphics g = Graphics.FromImage(bit);
                g.CompositingQuality = CompositingQuality.HighQuality;  //    质量设为最高
                g.CopyFromScreen(form.Left, form.Top, 0, 0, new Size(form.Width, form.Height)); //   保存整个窗体为图片

                //  检查是否存在文件夹
                if (!Directory.Exists(local_dir))
                {
                    //  创建文件夹
                    Directory.CreateDirectory(local_dir);
                }

                string now = DateTime.Now.ToString();
                now = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
                string path = local_dir + furnaceName + "_" + now + "_pic.jpg";

                bit.Save(path); //  保存到本地

                FileInfo file = new FileInfo(path);

                //  上传文件
                UploadFile(file, ftp_dir, ftp_url, ftp_username, ftp_password);

            }
            catch (Exception e)
            {
                throw e;
            }
        }




        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileinfo">需要上传的文件</param>
        /// <param name="targetDir">目标路径</param>
        /// <param name="hostname">ftp地址</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        private void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password) 
        {
            //1. check target
            if (targetDir.Trim() == "")
            {
                return;
            }

            //  先将targetDir两端的斜杠去掉
            while (targetDir.StartsWith("/"))
            {
                targetDir = targetDir.Substring(1);
            }
            while (targetDir.EndsWith("/"))
            {
                targetDir = targetDir.Substring(0, targetDir.Length - 1);
            }

            //  创建目录
            FtpMakeDir("ftp://" + hostname + "/", targetDir, username, password);

            string URI = "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name;

            FtpWebRequest ftp = null;
            try
            {
                //  根据服务器信息FtpWebRequest创建类的对象
                ftp = (FtpWebRequest)FtpWebRequest.Create(URI);
                //  提供身份验证信息
                ftp.Credentials = new NetworkCredential(username, password);
                //  设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
                ftp.KeepAlive = false;
                //  设置FTP命令 设置所要执行的FTP命令,
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
                //  指定文件传输的数据类型
                ftp.UseBinary = true;
                ftp.UsePassive = true;
                //  告诉ftp文件大小
                ftp.ContentLength = fileinfo.Length;
                //  缓冲大小设置为2KB
                const int BufferSize = 2048;
                byte[] content = new byte[BufferSize - 1 + 1];
                int dataRead;

                //  打开一个文件流 (System.IO.FileStream) 去读上传的文件
                using (FileStream fs = fileinfo.OpenRead())
                {
                    try
                    {
                        //  把上传的文件写入流
                        using (Stream rs = ftp.GetRequestStream())
                        {
                            do
                            {
                                //  每次读文件流的2KB
                                dataRead = fs.Read(content, 0, BufferSize);
                                rs.Write(content, 0, dataRead);
                            } while (!(dataRead < BufferSize));
                        }

                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (ftp != null)
                    ftp.Abort();
            }
        }


        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="ftp">ftp地址,例如:"ftp://127.0.0.1/"</param>
        /// <param name="path">要创建的目录,例如:aps/image</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        private void FtpMakeDir(string ftp, string path, string username, string password)
        {
            //  如果不再包含斜杠,则直接创建该目录
            if (!path.Contains('/'))
            {
                FtpMakeDirFile(ftp, path, username, password);
                return;
            }

            //  包含斜杠,则分级创建目录
            string[] s = path.Split('/');
            string createPath = "";
            for (int i = 0; i < s.Length; i++)
            {
                createPath = createPath + s[i] + "/";
                FtpMakeDirFile(ftp, createPath, username, password);
            }
        }


        /// <summary>
        /// 创建每一级的目录
        /// </summary>
        /// <param name="ftp">ftp地址,例如:"ftp://127.0.0.1/"</param>
        /// <param name="dirName">目录名称</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        private void FtpMakeDirFile(string ftp, string dirName, string username, string password)
        {
            string uri = ftp + dirName;

            FtpWebRequest req = null;
            FtpWebResponse resp = null;

            try
            {
                req = (FtpWebRequest)WebRequest.Create(uri);
                req.Credentials = new NetworkCredential(username, password);
                req.Method = WebRequestMethods.Ftp.MakeDirectory;
                resp = (FtpWebResponse)req.GetResponse();
            }
            catch (Exception)
            {
            }
            finally
            {
                if (resp != null)
                    resp.Close();
                if (req != null)
                    req.Abort();
            }
        } 
    }
}

 

标签:FTP,string,ftp,C#,System,targetDir,窗体,using,password
来源: https://www.cnblogs.com/tan-cong/p/14710514.html