标签: webclient

在C#中暂停/恢复上传

我正在寻找一种通过C#的WebClient暂停或恢复上传过程的方法.

伪代码:

WebClient Client = new WebClient();
Client.UploadFileAsync(new Uri("http://mysite.com/receiver.php"), "POST", "C:\MyFile.jpg");

也许像..

Client.Pause();

任何的想法?

c# upload webclient

3
推荐指数
1
解决办法
3905
查看次数

C#WebClient内存使用情况

我正在使用WebClient,DownloadString(" http://example.com/string.txt "); 当我调用它时,内存会跳起来,但永远不会再下降,因为我需要从网上下载2-3个不同的字符串,所以内存会大大增加.

我是C#的新手并且还在学习,但是从网上下载字符串之后是否还要清除内存?如果没有,你知道我可以使用任何其他方法从网上读取更少的内存吗?

谢谢

c# memory webclient

3
推荐指数
1
解决办法
4145
查看次数

为什么这个异常声称代码不写数据?

如果您运行此代码,它将抛出WebException.内部异常是"无法为不写入数据的操作设置Content-Length或Chunked Encoding".我不明白问题的本质.任何人都可以将光投射到这个黑暗角落吗

using System.Diagnostics;
using System.Net;
using System.Text;

namespace sandpit
{
  static class Program
  {
    static void Main()
    {
      string INITIAL_URI = "http://docs.live.net/SkyDocsService.svc";
      string SOAP = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><GetWebAccountInfoRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://schemas.microsoft.com/clouddocuments\"><BaseRequest><ClientAppId>SkyDrive Service Client</ClientAppId><Market>en-US</Market><SkyDocsServiceVersion>v1.0</SkyDocsServiceVersion></BaseRequest><GetReadWriteLibrariesOnly>false</GetReadWriteLibrariesOnly></GetWebAccountInfoRequest></s:Body></s:Envelope>";
      using (WebClient wc = new WebClient())
      {
        wc.Encoding = Encoding.UTF8;
        wc.Headers["SOAPAction"] = "GetWebAccountInfo";
        wc.Headers["Accept-Language"] = "en-US";
        wc.Headers["Accept"] = "text/xml";
        wc.Headers["Content-Type"] = "text/xml; charset=utf-8";
        string response = wc.UploadString(INITIAL_URI, SOAP);
        Debug.WriteLine(response);
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

c# webclient onedrive

3
推荐指数
1
解决办法
5510
查看次数

使用WebClient下载torrent文件会导致文件损坏

我正在尝试在我的.NET应用程序中下载.torrent文件(不是torrent本身的内容).

使用以下代码适用于其他文件,但不适用于.torrent.生成的文件比通过浏览器下载文件小约1-3kb.在torrent客户端打开它时,它说洪流已损坏.

WebClient web = new WebClient();
web.Headers.Add("Content-Type", "application/x-bittorrent");
web.DownloadFile("http://kat.ph/torrents/linux-mint-12-gnome-mate-dvd-64-bit-t6008958/", "test.torrent");
Run Code Online (Sandbox Code Playgroud)

在浏览器中打开URL会导致文件正确下载.

有关为什么会发生这种情况的任何想法?是否有正确下载文件的WebClient有什么好的替代方案?

编辑:我和WebClient一样尝试了这个,它导致了同样的事情:

private void DownloadFile(string url, string file)
    {
        byte[] result;
        byte[] buffer = new byte[4096];

        WebRequest wr = WebRequest.Create(url);
        wr.ContentType = "application/x-bittorrent";
        using (WebResponse response = wr.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = responseStream.Read(buffer, 0, buffer.Length);
                        memoryStream.Write(buffer, 0, count);

                    } while (count != 0);

                    result = memoryStream.ToArray();

                    using (BinaryWriter writer = …
Run Code Online (Sandbox Code Playgroud)

.net c# webclient

3
推荐指数
1
解决办法
3090
查看次数

HttpRequestHeader内容编码问题

我使用下面的代码片段将HTTP响应下载到本地文件.有时,我在url中的内容是多语言的(中文,日文,泰文数据等).我使用ContentEncoding标头指定我的内容是UTF-8编码,但这对我的本地输出文件没有影响,该文件是用ASCII生成的.因此,多语言数据已损坏.有帮助吗?

using (var webClient = new WebClient())
        {
            webClient.Credentials = CredentialCache.DefaultCredentials;
            webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0");
            webClient.Headers.Add(HttpRequestHeader.ContentEncoding, "utf-8");

            webClient.DownloadFile(url, @"c:\temp\tempfile.htm");
        }
Run Code Online (Sandbox Code Playgroud)

c# encoding webclient

3
推荐指数
1
解决办法
7300
查看次数

Howto:下载保存C#原始名称的文件?

我有一个服务器上的文件,可以从这样格式的URL访问:http:// address/Attachments.aspx?id = GUID

我可以访问GUID,并且需要能够将多个文件下载到同一文件夹.

如果你把这个URL扔到浏览器中,你将下载该文件,它将具有原始文件名.

我想在C#中复制该行为.我尝试过使用WebClient类的DownloadFile方法,但是必须指定一个新的文件名.更糟糕的是,DownloadFile将覆盖现有文件.我知道我可以为每个文件生成一个唯一的名称,但我真的很喜欢原始文件.

是否可以下载保留原始文件名的文件?

更新:

使用下面的精彩答案来使用WebReqest类,我提出了以下完美的工作:

    public override void OnAttachmentSaved(string filePath)
    {
        var webClient = new WebClient();

        //get file name
        var request = WebRequest.Create(filePath);
        var response = request.GetResponse();
        var contentDisposition = response.Headers["Content-Disposition"];
        const string contentFileNamePortion = "filename=";
        var fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
        var originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
        var originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);

        //download file
        webClient.UseDefaultCredentials = true;
        webClient.DownloadFile(filePath, String.Format(@"C:\inetpub\Attachments Test\{0}", originalFileName));            
    }
Run Code Online (Sandbox Code Playgroud)

只需要进行一些字符串操作即可获得实际的文件名.我太激动了.感谢大家!

c# webclient download

3
推荐指数
1
解决办法
8115
查看次数

尝试捕捉不起作用

class XWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri Url)
    {
        var Request = base.GetWebRequest(Url);
        ...........
        return Request;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用:

try
{
    XWebClient Client = new XWebClient();
    Client.DownloadString(new Uri("badurl:100500"));
}
catch
{
    MessageBox.Show("exception");
}
Run Code Online (Sandbox Code Playgroud)

我希望得到一个消息框,但我得到一个未处理的异常.我究竟做错了什么?


例外:System.NotSupportedexception

消息:无法识别URI前缀

跟踪:

   System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
   System.Net.WebRequest.Create(Uri requestUri)
   System.Net.WebClient.GetWebRequest(Uri address)
   XWebClient.GetWebRequest(Uri Url) ? [path]\XWebClient.cs:?????? 28
   System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
Run Code Online (Sandbox Code Playgroud)

c# webclient exception try-catch

3
推荐指数
1
解决办法
2184
查看次数

DownloadString为https网址提供了超时,似乎可以在浏览器中使用

我试图将此URL中的内容导入我的程序:https://data.mtgox.com/api/2/BTCUSD/money/ticker.在我的任何浏览器中访问URL时,它都可以正常运行.

但是在我的程序中,它会等待90秒,并给我一个超时.

这是我的代码:

    private const string ApiLnk = "https://data.mtgox.com/api/2/BTCUSD/money/ticker";

    static void Main(string[] args)
    {
        using (WebClient client = new WebClient())
        {
            string s = client.DownloadString(ApiLnk);
            int i = 0;
        }
    }
Run Code Online (Sandbox Code Playgroud)

字符串s永远不会被分配,因为client.DownloadString()是一个停止.

获得像Google.com这样的普通网址时,它的效果非常好.

知道什么是错的吗?

c# https json webclient

3
推荐指数
1
解决办法
3802
查看次数

PostAsync方法的HttpClient错误

使用HttpClient对第三方API进行PostAsync调用时.当我做client.PostAsync时,我正好看到这个错误.知道是什么导致了这个吗?

码:

public class JobController : AsyncController
{
    public ActionResult ViewPage()
    {
        return View("~/Views/Pages/Submit.cshtml");
    }

    private const string ServiceUrl = "https://api.3points.io/v1/applications/";

    [HttpPost]
    public async Task<ActionResult> Submit()
    {
        var client = new HttpClient();
        var formData = new MultipartFormDataContent();
        var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("abc123"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);

        foreach (var key in Request.Form.AllKeys)
            formData.Add(new StringContent(Request.Form[key]), String.Format("\"{0}\"", key));

        foreach (string key in Request.Files.AllKeys)
        {
            var file = Request.Files[key];
            if (file == null || file.ContentLength <= 0) continue;

            HttpContent fileStream = new StreamContent(file.InputStream);
            formData.Add(fileStream, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc webclient

3
推荐指数
1
解决办法
1万
查看次数

底层连接已关闭:发生意外错误

我有一个非常简单的服务,它调用URL并捕获由该服务写出的状态;

// Service call used to determine availability
System.Net.WebClient client = new System.Net.WebClient();

// I need this one (sorry, cannot disclose the actual URL)
Console.WriteLine(client.DownloadString(myServiceURL + ";ping"));

// I added this for test purposes
Console.WriteLine(client.DownloadString("https://www.google.com"));
Run Code Online (Sandbox Code Playgroud)

myServiceURL行的"DownloadString"引发错误"底层连接已关闭:发生了意外错误",Fiddler中没有显示此行,而google.com的"DownloadString"工作正常,我看到控制台输出.

根据错误的其他建议,我尝试了设置UseDefaultCredentials,编码选项,为请求添加适当的标头的组合,这些都没有任何区别.

client.UseDefaultCredentials = true;
client.Encoding = Encoding.UTF8;
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中导航到myServiceURL时,它正常工作,并按预期显示"OK".

来自同一服务的另一种方法编码如下:

// Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(myServiceURL + ";login");

// Set the request configuration options
req.Method = "POST";
req.ContentType = "text/xml";
req.ContentLength = bytes.Length;
req.Timeout = -1;

// Call for the request stream
using (Stream os …
Run Code Online (Sandbox Code Playgroud)

c# web-services webclient webrequest

3
推荐指数
1
解决办法
8696
查看次数