23

HTTP を使用してファイルをローカル ディレクトリにダウンロードする組み込みの方法はありますか?

wget をシェルアウトしたり、カスタム タスクを作成したりできますが、これを実現する既存の方法がないことを確認したかったのです。

前もって感謝します!

4

5 に答える 5

28

MSBuild 4.0 では、インライン タスクを使用して、別のアセンブリでカスタム タスクをコンパイルおよび展開する必要がなくなります。

  <UsingTask TaskName="DownloadFile" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
    <ParameterGroup>
      <Address ParameterType="System.String" Required="true"/>
      <FileName ParameterType="System.String" Required="true" />
    </ParameterGroup>
    <Task>
      <Reference Include="System" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
            new System.Net.WebClient().DownloadFile(Address, FileName);
        ]]>
      </Code>
    </Task>
  </UsingTask>

  <Target Name="DownloadSomething">
    <DownloadFile Address="http://somewebsite/remotefile" FileName="localfilepath" />
  </Target>
于 2012-10-05T03:43:09.777 に答える
13

MSBuild Community Tasksには、必要と思われる WebDownload というタスクがあります。

于 2009-07-06T22:24:20.900 に答える
11

認証が必要なファイル (TFS Web、またはドメインに接続された IIS サーバーなど) をダウンロードしようとしている場合、MSBuild 拡張パックも MSBuild コミュニティ タスクも、ユーザー名またはパスワードを与える機能を持っていないようです。 HTTP サーバー。この場合、カスタム MSBuild タスクを作成することになりました。これが私がしたことです。

vb.net/c# を使用して認証が必要なファイルをダウンロードするための彼の回答で、スタック オーバーフロー ユーザー Doug のアドバイスに従いました。で、Tom Archer が Code Guru Web サイトで作成したメソッドに追加するコードをいくつか提案しています。

そこで、MS Visual Studio 2010 を使用して、次のコードで新しい C# プロジェクトを作成し、Wget という名前の MSBuild ターゲットを作成しました (完全なソース コードを示します)。

// Include references to the following frameworks in your solution:
// - Microsoft.Build.Framework
// - Microsoft.Build.Utilities.v4.0
// - System
// - System.Net

using System;
using System.Net;
using System.IO;

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Wget
{
    public class Wget: Task
    {
        [Required]
        public String Address // HTTP address to access
        { get; set; }

        [Required]
        public String LocalFilename // Local file to which the downloaded page will be saved
        { get; set; }

        public String Username // Credential for HTTP authentication
        { get; set; }

        public String Password // Credential for HTTP authentication
        { get; set; }

        public override bool Execute()
        {
            int read = DownloadFile(Address, LocalFilename, Username, Password);

            Console.WriteLine("{0} bytes written", read);

            return true;
        }

        public static int DownloadFile(String remoteFilename, String localFilename, String httpUsername, String httpPassword)
        {
            // Function will return the number of bytes processed
            // to the caller. Initialize to 0 here.
            int bytesProcessed = 0;

            // Assign values to these objects here so that they can
            // be referenced in the finally block
            Stream remoteStream = null;
            Stream localStream = null;
            WebResponse response = null;

            // Use a try/catch/finally block as both the WebRequest and Stream
            // classes throw exceptions upon error
            try
            {
                // Create a request for the specified remote file name
                WebRequest request = WebRequest.Create(remoteFilename);
                if (request != null)
                {
                    // If a username or password have been given, use them
                    if (httpUsername.Length > 0 || httpPassword.Length > 0)
                    {
                        string username = httpUsername;
                        string password = httpPassword;
                        request.Credentials = new System.Net.NetworkCredential(username, password);
                    }

                    // Send the request to the server and retrieve the
                    // WebResponse object 
                    response = request.GetResponse();
                    if (response != null)
                    {
                        // Once the WebResponse object has been retrieved,
                        // get the stream object associated with the response's data
                        remoteStream = response.GetResponseStream();

                        // Create the local file
                        localStream = File.Create(localFilename);

                        // Allocate a 1k buffer
                        byte[] buffer = new byte[1024];
                        int bytesRead;

                        // Simple do/while loop to read from stream until
                        // no bytes are returned
                        do
                        {
                            // Read data (up to 1k) from the stream
                            bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

                            // Write the data to the local file
                            localStream.Write(buffer, 0, bytesRead);

                            // Increment total bytes processed
                            bytesProcessed += bytesRead;
                        } while (bytesRead > 0);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // Close the response and streams objects here 
                // to make sure they're closed even if an exception
                // is thrown at some point
                if (response != null) response.Close();
                if (remoteStream != null) remoteStream.Close();
                if (localStream != null) localStream.Close();
            }

            // Return total bytes processed to caller.
            return bytesProcessed;
        }
    }
}

これで、次のタスクを MSBuild プロジェクトに追加できます。

<!-- Get the contents of a Url-->
<Wget
    Address="http://mywebserver.com/securepage"
    LocalFilename="mydownloadedfile.html"
    Username="myusername"
    Password="mypassword">
</Wget>

Wget タスクは、mywebserver.com が提供するページをダウンロードし、ユーザー名 "myusername" とパスワード "mypassword" を使用して、現在の作業ディレクトリに mydownloadedfile.html としてファイルに保存します。

ただし、カスタム Wget MSBuild タスクを使用するには、Wget アセンブリ ファイル (.dll) の場所を MSBuild に指示する必要があります。これは、MSBuild の要素で行われます。

<!-- Import your custom MSBuild task -->
<UsingTask AssemblyFile="MyCustomMSBuildTasks\Wget\bin\Release\Wget.dll" TaskName="Wget" />

より凝ったものにしたい場合は、MSBuild プロジェクトが呼び出される前に Wget をビルドすることもできます。これを行うには、タスクを使用してソリューションをビルドし、<MSBuild Projects>タスクを使用してインポートし<UsingTaks AssemblyFile>ます。次のようにします。

<!-- Build the custom MSBuild target solution-->
<MSBuild Projects="MyCustomMSBuildTasks\CustomBuildTasks.sln" Properties="Configuration=Release" />

<!-- Import your custom MSBuild task -->
<UsingTask AssemblyFile="MyCustomMSBuildTasks\Wget\bin\Release\Wget.dll" TaskName="Wget" />

<!-- Get the contents of a Url-->
<Wget
    Address="http://mywebserver.com/securepage"
    LocalFilename="mydownloadedfile.html"
    Username="myusername"
    Password="mypassword">
</Wget>

以前にカスタム MSBuild ターゲットを作成したことがなくても、基本を理解していればそれほど難しくありません。上記の C# コードを見て、MSDN の公式ドキュメントを見て、Web で他の例を検索してください。開始するのに適した場所は次のとおりです。

于 2011-06-02T22:11:14.060 に答える
1

MSBuild コミュニティ タスク プロジェクトの WebDownload タスクに加えて、MSBuild 拡張機能パック (現在のバージョン: 4.x) にはWebClient、ファイルのダウンロードに使用できるクラスがあります。MSBuild 拡張パックは、次の場所からダウンロードできます。

MSBuild Extension Pack 4 を使用してファイルをダウンロードする例を次に示します。

<Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
    <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
    <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
</PropertyGroup>
<Import Project="$(TPath)"/>
<Target Name="Default">
    <!-- Download a File-->
    <MSBuild.ExtensionPack.Web.WebClient TaskAction="DownloadFile" Url="http://hlstiw.bay.livefilestore.com/y1p7GhsJWeF4ig_Yb-8QXeA1bL0nY_MdOGaRQ3opRZS0YVvfshMfoZYe_cb1wSzPhx4nL_yidkG8Ji9msjRcTt0ew/Team%20Build%202008%20DeskSheet%202.0.pdf?download" FileName="C:\TFS Build 2008 DeskSheet.pdf"/>
    <!-- Get the contents of a Url-->
    <MSBuild.ExtensionPack.Web.WebClient TaskAction="OpenRead" Url="http://www.msbuildextensionpack.com">
        <Output TaskParameter="Data" PropertyName="Out"/>
    </MSBuild.ExtensionPack.Web.WebClient>
    <Message Text="$(Out)"/>
</Target>

別の回答で述べたようにWebClient、安全な (パスワードで保護された) Web サーバーからダウンロードする機能がないようです。

于 2011-06-02T19:27:45.647 に答える