使用WebClient类上传文件

来源:互联网 发布:人工智能国际会议 编辑:程序博客网 时间:2024/05/06 21:28

我要在windows模式下上传文件,找了好久才找到,现在把他写下来,帮助后来者

方法一

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            WebClient webClient = new WebClient();
            webClient.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                //方法一
                FileStream fs = new FileStream(@"d:/filetxt.txt", FileMode.Open, FileAccess.Read);
               
                BinaryReader r = new BinaryReader(fs);


                byte[] postArray = r.ReadBytes((int)fs.Length);
                Stream postStream = webClient.OpenWrite(@"http://10.227.34.174/upload/filetxt.txt", "PUT");
                if (postStream.CanWrite)
                {
                    postStream.Write(postArray, 0, postArray.Length);
                    Console.WriteLine("Success!");
                }
                else
                {
                    Console.WriteLine("Fail!");
                }
                postStream.Close();

                ////方法二
                //webClient.UploadFile(@"http://10.227.34.174/upload/filetxt.txt", "PUT", @"d:/filetxt.txt");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

 

方法二

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            WebClient webClient = new WebClient();
            webClient.Credentials = CredentialCache.DefaultCredentials;
            try
            {               
                //方法二
                webClient.UploadFile(@"http://10.227.34.174/upload/filetxt.txt", "PUT", @"d:/filetxt.txt");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }