2017-04-17 30 views
0

Visual Studio Community 2015でテキストファイルをダウンロードできません。アプリケーション(1.0.0.0)のバージョン番号を含むOneDrive Publicフォルダのテキストファイルです。私が使用するダウンロードリンクは、手動で開くと完全に動作しますが、VBコードが実行されると、テキストファイルが正しくダウンロードされますが、ファイルを開くと空白になり、どこが間違っているのか分かりません。 Module1のでVB.NETでオンラインテキストファイルが空白になっているのはなぜですか?

、私はダウンロードして、その後、ファイルを読み込むためのサブのためのサブあります

Module Module1 

    ' Public variables 

    Public tempPath As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\Temp" 

    Sub DownloadToTemp(filePath As String) 
     ' Download a text file, ready to read contents 

     If Not IO.Directory.Exists(tempPath & "\Temp") Then 
      IO.Directory.CreateDirectory(tempPath & "\Temp") 
     End If 

     Try 
      My.Computer.Network.DownloadFile _ 
       (address:=filePath, 
       destinationFileName:=tempPath & "\TempText.txt", 
       userName:=String.Empty, 
       password:=String.Empty, 
       showUI:=False, 
       connectionTimeout:=10000, 
       overwrite:=True) 

     Catch ex As Exception 
      MsgBox("Can't read file" & vbCrLf & ex.Message) 
     End Try 

    End Sub 

    Sub ReadFile() 

     Dim fStream As New IO.FileStream(tempPath & "\TempText.txt", IO.FileMode.Open) 
     Dim sReader As New System.IO.StreamReader(fStream) 
     Dim sArray As String() = Nothing 
     Dim index As Integer = 0 

     Do While sReader.Peek >= 0 
      ReDim Preserve sArray(index) 
      sArray(index) = sReader.ReadLine 
      index += 1 
     Loop 

     fStream.Close() 
     sReader.Close() 

     ' Test 
     Dim fileContents As String = Nothing 
     If sArray Is Nothing Then 
      MsgBox("No Data Found") 
      Exit Sub 
     End If 
     For index = 0 To UBound(sArray) 
      fileContents = fileContents & sArray(index) & vbCrLf 
     Next 

     MessageBox.Show(fileContents) 

    End Sub 

End Module 

を、それらがメインコードから呼び出されている:だから

Private Sub frmSplash_Load(sender As Object, e As EventArgs) Handles MyBase.Load 

    lblVersion.Text = "v" & Application.ProductVersion 

    ' Check available version online 

    Call DownloadToTemp("https://onedrive.live.com/download?resid=DE2331D1649390C1!16974&authkey=!AH2cr1S1SHs9Epk&ithint=file%2ctxt") 
    Call ReadFile() 

End Sub 

、すべてがそうですエラーや例外は発生しませんが、VBコードがダウンロードするファイルは空白ですが、コードからダウンロードリンクを手動でクリックすると内容はそのままダウンロードされます。なぜこれが起こっているのか誰にも見えますか?

+0

@VisualVincent印象。私は直接ダウンロードリンクを取得する方法を見つけるためにもう一度試しましたが、Microsoftが意図的に避けているようです。リダイレクトを許可する代わりに、私は間違いなくHttpWebRequestクラスコードを使用します。再度、感謝します! – JasonPy

+0

うれしい私は助けることができました!私は私の答えのコメントを見たので、ダブルポストする必要はありません。 ;) –

答えて

1

コードはその場所にあるものをダウンロードしますが、そのリンクはあなたを別の場所にリダイレクトするように見えます。リンクから取得した応答をダウンロードします。何もないので何もありません。

正常に動作するにはファイルへの直接リンクが必要です。代わりにこれを試してください:

DownloadToTemp("https://gwhcha-dm2306.files.1drv.com/y4mwlpYyvyCFDPp3NyPM6WqOz8-Ocfn-W0_4RbdQBtNMATYn2jNgWMRgpl_gXdTBteipIevz07_oUjCkeNoJGUxNO9jC9IdXz60NNEvzx2cU9fYJU_oRgqBFyA8KkBs8VGc8gDbs2xz7d3FyFnkgRfq77A2guoosQkO4pVMDiEYRoJRCWOtQk2etsMXyT8nSEnPoGV6ZG0JWc6qt55Mhi_zeA/Hotshot_Version.txt?download&psid=1") 

また、Call keywordを使用する必要はありません。 VB6およびそれ以前のバージョンとの下位互換性のためにのみ存在します。


EDIT:

ここではHttpWebRequest classを使用してファイルをダウンロードする例を示します。 AllowAutoRedirectMaximumAutomaticRedirectionsのプロパティを設定すると、ファイルをダウンロードしようとする前にリダイレクトできるようになります。

''' <summary> 
''' Downloads a file from an URL and allows the page to redirect you. 
''' </summary> 
''' <param name="Url">The URL to the file to download.</param> 
''' <param name="TargetPath">The path and file name to download the file to.</param> 
''' <param name="AllowedRedirections">The maximum allowed amount of redirections (default = 32).</param> 
''' <param name="DownloadBufferSize">The amount of bytes of the download buffer (default = 4096 = 4 KB).</param> 
''' <remarks></remarks> 
Private Sub DownloadFileWithRedirect(ByVal Url As String, _ 
            ByVal TargetPath As String, _ 
            Optional ByVal AllowedRedirections As Integer = 32, _ 
            Optional ByVal DownloadBufferSize As Integer = 4096) 
    'Create the request. 
    Dim Request As HttpWebRequest = DirectCast(WebRequest.Create(Url), HttpWebRequest) 
    Request.Timeout = 10000 '10 second timeout. 
    Request.MaximumAutomaticRedirections = AllowedRedirections 
    Request.AllowAutoRedirect = True 

    'Get the response from the server. 
    Using Response As HttpWebResponse = DirectCast(Request.GetResponse(), HttpWebResponse) 
     'Get the stream to read the response. 
     Using ResponseStream As Stream = Response.GetResponseStream() 

      'Declare a download buffer. 
      Dim Buffer() As Byte = New Byte(DownloadBufferSize - 1) {} 
      Dim ReadBytes As Integer = 0 

      'Create the target file and open a file stream to it. 
      Using TargetFileStream As New FileStream(TargetPath, FileMode.Create, FileAccess.Write, FileShare.None) 

       'Start reading into the buffer. 
       ReadBytes = ResponseStream.Read(Buffer, 0, Buffer.Length) 

       'Loop while there's something to read. 
       While ReadBytes > 0 
        'Write the read bytes to the file. 
        TargetFileStream.Write(Buffer, 0, ReadBytes) 

        'Read more into the buffer. 
        ReadBytes = ResponseStream.Read(Buffer, 0, Buffer.Length) 
       End While 

      End Using 

     End Using 
    End Using 
End Sub 

使用例:

Try 
    DownloadFileWithRedirect("https://onedrive.live.com/download?resid=DE2331D1649390C1!16974&authkey=!AH2cr1S1SHs9Epk&ithint=file%2ctxt", Path.Combine(tempPath, "TempText.txt")) 
Catch ex As Exception 
    MessageBox.Show("An error occurred:" & Environment.NewLine & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 
End Try 
+0

優秀!それは完璧に働いた、ありがとう。直接リンクをどのように管理できたか教えてください。リダイレクトを変換する式はありますか? – JasonPy

+0

@JasonVB:iPhoneのSafari Webブラウザは、あなたが何をしたいのかを尋ねるのではなく、プレーンテキストファイルの内容を表示するだけなので、それを得ました。したがって、タイトルバーからダイレクトリンクをコピーするだけでした。 - あなたは直接リンクを得ることができる他の方法があります、私に数分を与えると私は何かを見つけることができるはずです。 –

+0

@JasonVB:明らかに、 'HttpWebRequest'クラスはリダイレクトを許可するように設定できます。これを見てください:http://stackoverflow.com/a/11749745/3740093(これはC#ですが、オンラインコンバータを使って簡単に変換できます)。 –

関連する問題