winform 查看远程服务器上的文件

解决方案:

1. 在目标服务器上发布webservice,实现文件下载的方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Data;

namespace TRNWebService
{
    /// <summary>
    /// FileHelperService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class FileHelperService : System.Web.Services.WebService
    {
       
        /// <summary>
        /// 从指定文件夹下获取文件
        /// </summary>
        /// <param name="dicpath"></param>
        /// <returns></returns>
        [WebMethod(EnableSession = true, Description = "获取文件夹下面的文件")]
        public  DataTable GetFileList(string dicpath)
        {
            DataTable dt = new DataTable();
            dt.TableName = "AEFiles";
            dt.Columns.Add("fileName", typeof(string));
            dt.Columns.Add("filePath", typeof(string));
           

            DirectoryInfo dir = System.IO.Directory.CreateDirectory(dicpath);
            if (dir == null)
            {
                return null;
            }
            FileInfo[] files = dir.GetFiles();
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo file = files[i] as FileInfo;
                if (file != null)
                {
                    dt.Rows.Add(file.Name, file.FullName);
                }
            }

            return dt;

        }



        [WebMethod(Description = "下载服务器站点文件,传递文件相对路径")]
        public byte[] DownloadFile(string strFilePath)
        {
            FileStream fs = null; 
            //string CurrentUploadFolderPath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UploadFileFolder"]);
            //string CurrentUploadFilePath = CurrentUploadFolderPath + strFilePath;
            string CurrentUploadFilePath = strFilePath;
            if (File.Exists(CurrentUploadFilePath))
            {
                try
                {
                    ///打开现有文件以进行读取。
                    fs = File.OpenRead(CurrentUploadFilePath);
                    int b1;
                    System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
                    while ((b1 = fs.ReadByte()) != -1)
                    {
                        tempStream.WriteByte(((byte)b1));
                    }
                    return tempStream.ToArray();
                }
                catch (Exception ex)
                {
                    return new byte[0];
                }
                finally
                {
                    fs.Close();
                }
            }
            else
            {
                return new byte[0];
            }
        }
    }
}
webservice 下载文件

 

2. 客户端利用反射实现webservice,把文件下载到本地的安装目录

3. 客户端打开已经存放在本地的文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom.Compiler;
using System.Net;
using System.IO;
using Microsoft.CSharp;
using System.CodeDom;
using System.Web.Services.Description;

namespace Frm.Common
{
    public static class WebServiceInvoke
    {
        #region InvokeWebService
        //动态调用web服务
        public static object InvokeWebService(string url, string methodname, object[] args)
        {
            return InvokeWebService(url, null, methodname, args);
        }

        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "TRNWebService";
            if ((classname == null) || (classname == ""))
            {
                classname = GetWsClassName(url);
            }

            try
            {
                //获取WSDL
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler icc = csc.CreateCompiler();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }

        private static string GetWsClassName(string wsUrl)
        {
            string[] parts = wsUrl.Split('/');
            string[] pps = parts[parts.Length - 1].Split('.');

            return pps[0];
        }
        #endregion
    }
}
c# 利用反射实现动态webservice
 /// <summary>
        /// 通过WebService下载文件
        /// </summary>
        /// <param name="ServiceFilePath">服务器图片路径</param>
        /// <param name="DownloadFolderPath">本地图片路径</param>
        private string DownloadFile(string ServiceFilePath, string DownloadFolderPath)
        {
            try
            {
                string DownloadFileName = "";
                if (ServiceFilePath.Contains("/"))
                {
                    DownloadFileName = ServiceFilePath.Substring(ServiceFilePath.LastIndexOf("/"));
                }
                else if (ServiceFilePath.Contains("\\"))
                {
                    DownloadFileName = ServiceFilePath.Substring(ServiceFilePath.LastIndexOf("\\")+1);
                }
                else
                {
                    DownloadFileName = ServiceFilePath;
                }
            

                string DownloadFilePath = DownloadFolderPath + "\\" + DownloadFileName;

                Dictionary<string, string> dicSystem = Common.AppConfigSys.AppConfigDic;
                string strUrl = dicSystem["webserviceURL"];//webservice的发布位置(http://192.168.10.3:8084/FileHelperService.asmx)
                object[] objPara = new object[1];
                objPara[0] = ServiceFilePath;
                object objFile = Frm.Common.WebServiceInvoke.InvokeWebService(strUrl, "DownloadFile", objPara);



                byte[] bytes = (byte[])objFile; 
                if (bytes != null)
                {
                    if (!Directory.Exists(DownloadFolderPath))
                    {
                        Directory.CreateDirectory(DownloadFolderPath);
                    }
                    if (!File.Exists(DownloadFilePath))
                    {
                        File.Create(DownloadFilePath).Dispose();
                    }
                    //如果不存在完整的上传路径就创建
                    FileInfo downloadInfo = new FileInfo(DownloadFilePath);
                    if (downloadInfo.IsReadOnly) { downloadInfo.IsReadOnly = false; }
                    //定义并实例化一个内存流,以存放提交上来的字节数组。
                    MemoryStream ms = new MemoryStream(bytes);
                    //定义实际文件对象,保存上载的文件。
                    FileStream fs = new FileStream(DownloadFilePath, FileMode.Create);
                    ///把内内存里的数据写入物理文件
                    ms.WriteTo(fs);
                    fs.Flush();
                    ms.Flush();
                    ms.Close();
                    fs.Close();
                    fs = null;
                    ms = null;
                }
                return DownloadFilePath;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
客户端文件下载方法
  void AElink_Click(object sender, EventArgs e)
        {

            LinkLabel link = sender as LinkLabel;
            string serverfilePath = link.Tag.ToString();//服务器上的文件地址

            string clientfilePath = DownloadFile(serverfilePath, Application.StartupPath + "\\UploadFileFolder");//客户端的文件地址
            System.Diagnostics.Process.Start(clientfilePath);//打开本地文件
     
        }
文件下载方法调用

 

posted on 2015-10-27 15:52  eye_like  阅读(1908)  评论(0编辑  收藏  举报