• 网络学院
  • 新手学堂
  • 操作系统
  • 网络技术
  • 软件应用
  • 办公软件
  • 编程技术
  • 网站架设
  • 数据库类
  • 平面设计
  • 多媒体类
  • 游戏资讯
  • 教学论文
  • 认证考试
利用WebClient类向服务器上载文件
广告位
  站点:
  • 首 页
  • 最新软件
  • 最新文章
  • 国内软件
  • 国外软件
  • 汉化软件
  • 源码下载
  • 字体下载
利用WebClient类向服务器上载文件
软件发布 利用WebClient类向服务器上载文件
网络软件 系统工具 应用软件 联络聊天 图形图像 多媒体类 行业软件 游戏娱乐 编程开发 安全相关 教育教学 数码软件
热门软件: QQ 瑞星 pplive e话通 木马克星 千千静听 office2000 五笔字根 Photoshop 视频分割
返回首页 | 文章首页 | 编程技术 | C#教程 | 利用WebClient类向服务器上载文件

利用WebClient类向服务器上载文件

 

添加时间: 2007-7-13 1:54:19  作者: C#教程  阅读次数:30   来源: http://www.d9soft.com

 

 

       

.net 提供了许多上载文件的方法,在Windows Form应用程序中,我们可以使用WebClient类来实现。WebClient类也有两个方法可以上载,UploadFile和OpenWrite方法,下面就是一个实际的例子,两种方法都有代码:

结果如下:

 

C#代码如下:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Text;
using System.IO;


namespace UploadFile
{
  public class Form1 : System.Windows.Forms.Form
  {
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.TextBox txtFileName;
    private System.Windows.Forms.TextBox txtServ<a href="http://dev.21tx.com/corp/solution/erp/" target="_blank">ERP</a>ath;
    private System.Windows.Forms.LinkLabel linkLabel1;
 
    private System.ComponentModel.Container components = null;

    public Form1()
    {
      InitializeComponent();
    }
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null)
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    private void InitializeComponent()
    {
      System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
      this.label1 = new System.Windows.Forms.Label();
      this.txtServerPath = new System.Windows.Forms.TextBox();
      this.label2 = new System.Windows.Forms.Label();
      this.button1 = new System.Windows.Forms.Button();
      this.txtFileName = new System.Windows.Forms.TextBox();
      this.label3 = new System.Windows.Forms.Label();
      this.button2 = new System.Windows.Forms.Button();
      this.linkLabel1 = new System.Windows.Forms.LinkLabel();
      this.SuspendLayout();
      //
      // label1
      //
      this.label1.ForeColor = System.Drawing.Color.Red;
      this.label1.Location = new System.Drawing.Point(8, 96);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(448, 16);
      this.label1.TabIndex = 0;
      this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      //
      // txtServerPath
      //
      this.txtServerPath.Location = new System.Drawing.Point(128, 8);
      this.txtServerPath.Name = "txtServerPath";
      this.txtServerPath.Size = new System.Drawing.Size(320, 21);
      this.txtServerPath.TabIndex = 1;
      this.txtServerPath.Text = "http://mengxianhui/<a href="http://dev.21tx.com/web/asp/" target="_blank">ASP</a>xWeb/Images/";
      //
      // label2
      //
      this.label2.AutoSize = true;
      this.label2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold,
                                  System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
      this.label2.ForeColor = System.Drawing.Color.Navy;
      this.label2.Location = new System.Drawing.Point(8, 12);
      this.label2.Name = "label2";
      this.label2.Size = new System.Drawing.Size(116, 17);
      this.label2.TabIndex = 2;
      this.label2.Text = "请输入<a href="http://www.21tx.com/server/" target="_blank">服务器</a>地址:";
      this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      //
      // button1
      //
      this.button1.Location = new System.Drawing.Point(192, 64);
      this.button1.Name = "button1";
      this.button1.TabIndex = 3;
      this.button1.Text = "上载文件";
      this.button1.Click += new System.EventHandler(this.button1_Click);
      this.button1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.button1_MouseDown);
      //
      // txtFileName
      //
      this.txtFileName.Location = new System.Drawing.Point(128, 32);
      this.txtFileName.Name = "txtFileName";
      this.txtFileName.Size = new System.Drawing.Size(232, 21);
      this.txtFileName.TabIndex = 4;
      this.txtFileName.Text = "";
      //
      // label3
      //
      this.label3.AutoSize = true;
      this.label3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold,
                                  System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
      this.label3.ForeColor = System.Drawing.Color.DarkBlue;
      this.label3.Location = new System.Drawing.Point(8, 38);
      this.label3.Name = "label3";
      this.label3.Size = new System.Drawing.Size(116, 17);
      this.label3.TabIndex = 5;
      this.label3.Text = "请输入上传文件名:";
      this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      //
      // button2
      //
      this.button2.Location = new System.Drawing.Point(370, 32);
      this.button2.Name = "button2";
      this.button2.Size = new System.Drawing.Size(80, 23);
      this.button2.TabIndex = 6;
      this.button2.Text = "浏览文件…";
      this.button2.Click += new System.EventHandler(this.button2_Click);
      //
      // linkLabel1
      //
      this.linkLabel1.Location = new System.Drawing.Point(16, 120);
      this.linkLabel1.Name = "linkLabel1";
      this.linkLabel1.Size = new System.Drawing.Size(440, 24);
      this.linkLabel1.TabIndex = 7;
      this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
      this.linkLabel1.LinkClicked += new
        System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
      //
      // Form1
      //
      this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
      this.BackColor = System.Drawing.SystemColors.Control;
      this.ClientSize = new System.Drawing.Size(464, 157);
      this.Controls.Add(this.linkLabel1);
      this.Controls.Add(this.button2);
      this.Controls.Add(this.txtFileName);
      this.Controls.Add(this.label3);
      this.Controls.Add(this.txtServerPath);
      this.Controls.Add(this.label2);
      this.Controls.Add(this.button1);
      this.Controls.Add(this.label1);
      this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
      this.Name = "Form1";
      this.Text = "WebClient 上传文件的例子";
      this.Resize += new System.EventHandler(this.Form1_Resize);
      this.ResumeLayout(false);

    }
    #endregion
    [STAThread]
    static void Main()
    {
      Application.Run(new Form1());
    }

    /// <summary>
    /// .NET SDK 上面的打开文件的类
    /// </summary>

    private FileStream OpenFile()
    {
      OpenFileDialog dlgOpenFile = new OpenFileDialog();
      dlgOpenFile.ShowReadOnly = true;


      if(dlgOpenFile.ShowDialog() == DialogResult.OK)
      {
        if(dlgOpenFile.ReadOnlyChecked == true)
        {
          return (FileStream)dlgOpenFile.OpenFile();

        }
        else
        {
          string path = dlgOpenFile.FileName;
          return new FileStream(path, System.IO.FileMode.Open,
            System.IO.File<a href="http://dev.21tx.com/database/access/" target="_blank">Access</a>.ReadWrite);
        }
      }
      return null;
    }

    private void button2_Click(object sender, System.EventArgs e)
    {
      OpenFileDialog dlgOpenFile = new OpenFileDialog();
      dlgOpenFile.InitialDirectory = @"C:\";
      dlgOpenFile.ShowReadOnly = false;
      dlgOpenFile.ReadOnlyChecked = true;
      dlgOpenFile.Filter = "所有文件 (*.*)*.*";
      if(dlgOpenFile.ShowDialog() == DialogResult.OK)
      {
        if(dlgOpenFile.ReadOnlyChecked == true)
        {
          txtFileName.Text = dlgOpenFile.FileName.ToString();
        }
      }
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
      // 需要注意的是:txtServerPath文件夹有匿名可写的权限。
      // 可以自己定义新文件名字
      if(txtFileName.Text.Trim() == "" txtServerPath.Text.Trim() == "")
      {
        MessageBox.Show("请输入你要上载的文件名字!","错误:", MessageBoxButtons.OK,
                                                         MessageBoxIcon.Information);
      }
      else
      {
        /// 得到文件名,文件扩展名字,服务器路径
        string fileNamePath = txtFileName.Text.Trim();
        string uriString = txtServerPath.Text.Trim();
        string fileName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
        string fileNameExt = fileName.Substring(fileName.LastIndexOf(".") + 1);
        if(uriString.EndsWith("/") == false) uriString = uriString + "/";

        uriString = uriString + fileName;
        /// 创建WebClient实例
        WebClient myWebClient = new WebClient();
        myWebClient.Credentials = CredentialCache.DefaultCredentials;

        // 要上传的文件
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        //FileStream fs = OpenFile();
        BinaryReader r = new BinaryReader(fs);
        try
        {
          //使用UploadFile方法可以用下面的格式
          //myWebClient.UploadFile(uriString,"PUT",fileNamePath);
          byte[] postArray = r.ReadBytes((int)fs.Length);
          Stream postStream = myWebClient.OpenWrite(uriString,"PUT");
          if(postStream.CanWrite)
          {
            postStream.Write(postArray,0,postArray.Length);
            label1.Text = fileName + "上传成功!";
          }
          else
          {
            label1.Text = "文件目前不可写!";
          }
          postStream.Close();
          linkLabel1.Text = "查看上载的文件";
          for(int i = linkLabel1.Links.Count - 1;i>-1;i--)
          linkLabel1.Links.Remove(linkLabel1.Links[i]);
          linkLabel1.Links.Add(0,linkLabel1.Text.Length,uriString);         
        }
        catch(WebException errMsg)
        {
          label1.Text="上传失败:" + errMsg.Message;
        }
      }
    }

    private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
    {
      this.WindowState = FormWindowState.Minimized;
      this.linkLabel1.Links[linkLabel1.Links.IndexOf(e.Link)].Visited = true;
      string target = e.Link.LinkData as string;
      if(null != target)
      {
        System.Diagnostics.Process.Start(target);
      }
      else
      {   
        MessageBox.Show("请用浏览器访问:" + target);
      }
    }

    private void Form1_Resize(object sender, System.EventArgs e)
    {
      if(this.WindowState == FormWindowState.Maximized) this.WindowState = FormWindowState.Normal;
    }

    private void button1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
      if(txtFileName.Text.Trim() != "" && txtServerPath.Text.Trim() != "")
      label1.Text = "正在上传文件,请稍侯……!";
    } 
  }
}

 

 

 

上下文章:

 

上一篇文章: 在.NET中嵌入和使用资源文件 下一篇文章: 用设计模式固化C#程序

相关文章:

  • 卑鄙病毒:加密你的文件勒索你的钱
  • 端午节忠告:要警惕FLASH祝福文件里的包藏祸心
  • Oracle联机日志文件丢失处理方法
  • 黑客攻破SQL服务器系统的十种方法
  • servlet实现oracle中读出文件并显示

相关软件:

  • 木马文件粉碎机 V3.0
  • 北信源VRV 网络服务器端病毒库 89s
  • U-Mail V9.0 邮件服务器软件
  • 超级秘密文件夹 5.81
  • PE文件加区器 1.0
  • 文件备份专家 V2.55

 

 

快速导航

  • 网络学院
  • 精品汇聚
  • 字体下载
  • 教程下载
  • ASP源码
  • PHP源码
  • Net源码
  • JSP 源码

编程技术分类导航

  • ASP & ASP.NET教程
  • PHP教程
  • JSP教程
  • C/C++教程
  • VB & VB.NET教程
  • VC教程
  • Delphi教程
  • BCB教程
  • VFP教程
  • PB教程
  • JAVA教程
  • XML教程
  • C#教程
  • CGI教程

本类经典文章推荐

  • ADO.NET的开发场景及传统ADO的处理
  • 利用Visual C#实现Window管道技术
  • C#取得汉字的拼音的首字母
  • 使用C#编写DES加密程序的framework
  • Visual C#编写3D游戏框架示例
  • 用C#和本地Windows API操纵系统菜...
  • 在C#程序设计中使用Win32类库
  • Visual C#中调用Windows服务初探
  • 如何在C#的WinForm中制作饼状图和...
  • C#中实现DataGrid双向排序

C#教程阅读排行

  • 如何在C#的WinForm中制作饼状图和...
  • 浅析C#中图形编程
  • 用C#和本地Windows API操纵系统菜...
  • 彻底剖析C# 2.0泛型类的创建和使用
  • Visual C#编写3D游戏框架示例
  • 使用C#编写DES加密程序的framework
  • Visual C# 2005实现控件中捕获按键
  • Visual C#中调用Windows服务初探
  • C#如何在Form中嵌入并且操作Excel...
  • C#中利用mediaplayer打造mp3播放器

编程技术阅读总排行

  • VB入门教程之一
  • 第二章 PowerBuilder 入门之创建新...
  • Java连接数据库实例
  • 第一章 什么是PowerBuilder
  • VC++之List Box/Check List Box控...
  • VC++ List Ctrl控件
  • VC++ Combo Box/Combo Box Ex控件
  • 学C++不得不看的一篇文章
  • VB入门教程之二
  • VC++之Button控件

广告位置

字母检索 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 回到顶部

关于我们 | 版权声明 | 免责条款 | 广告联系 | 软件发布 | 下载帮助 | 下载排行 | 网站地图 | 特别鸣谢 | 友情连接

copyright; 2005-2008 D9soft.com 第九软件网 版权所有