不支持C#WebClient.DownloadFile从URL格式抓取CSV错误。

时间:2015-07-28 13:34:01

标签: c# webclient visual-studio-2015

快速提问。我试图做一个简单的控制台应用程序从URL获取文件。我希望我能说我更了解我正在抓取它的网站,但我所知道的是你把参数放到你想要的文件的URL中,当你转到URL时,你会自动开始下载对于它(这是在浏览器中发生的事情)。

所以我使用下面的代码,它确实创建了一个文件,但文件中的唯一文本是下面的消息。我尝试将文件名变量设置为与文件名相同,如果您只是通过浏览器下载它但是也没有用,同样的错误。有任何想法吗?

错误:

<?xml version="1.0" encoding="utf-8" ?><MtxExportingResult Result="Failure" Date="7/28/2015" Time="6:25:51 AM"><Error Type="FormatNotSupported">The format 'CSVExtract.csv' is not supported.</Error></MtxExportingResult>

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Net;

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

        string remoteUri = "https://www.downloadurl.com/ServerEPS/Export/AllFileRecords.xpt?IdentifierNumber=666&username=Username&password=Password&format=CSV";
        string fileName = "CPExtract.csv", myStringWebResource = null;

        WebClient cpClient = new WebClient();

        myStringWebResource = remoteUri + fileName;
        Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);

        cpClient.DownloadFile(myStringWebResource, fileName);
        Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
        Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t");


    }
}
}

任何建议将不胜感激。谢谢,

1 个答案:

答案 0 :(得分:1)

的结果
  

myStringWebResource = remoteUri + filename;

是一个格式错误的URI,以“&amp; format = CSVCPExtract.csv”结尾。

删除该行,您应该得到不同的结果。 (虽然你永远不会抓住我把这个URI放到浏览器或网络客户端......它看起来很可疑。)

下载文件的第一个参数是从中下载文件的URI。第二个是将其下载到的本地文件名。由于你的remoteUri包含参数,其中一个参数是IdentifierNumber,它似乎指向一个特定的文件。您从Web上复制和粘贴的代码执行此连接,因为它计划使用与远程服务器上的文件名相同的本地文件名。