WEBDav up-/download mit .NET 4

  • VB.NET
  • .NET (FX) 4.0

Es gibt 9 Antworten in diesem Thema. Der letzte Beitrag () ist von petaod.

    WEBDav up-/download mit .NET 4

    Moin zusammen,

    ich habe ein Programm geschrieben, welches Dateien auf einen WEBDav-Server hoch- und runterladt.
    Dazu habe ich die folgenden Funktionen/Beispiele gefunden:

    WEBDav Upload
    WebDav Download

    Funktioniert auf meinem PC auch sehr gut. Allerdings funktioniert es nicht mehr ab Framework 4.0

    Und ich komme nicht dahinter warum... Das muss irgendwas mit

    Quellcode

    1. System.Net.http
    zutun haben.

    Wenn ich es richtig verstanden habe, gibt es das im Framework 4 nicht mehr.

    Kann mir einer helfen, die Funktion für das 4er abzuändern?

    Hier nochmal die Funktionen:

    Spoiler anzeigen

    VB.NET-Quellcode

    1. Public Function XML_hochladen(ByVal Dateipfad As String, ByVal Serverpfad As String, ByVal ConPort As String, ByVal Benutzername As String, ByVal Passwort As String) As Boolean
    2. 'C: The first thing we can do is get the path of the file, and it's length.
    3. Dim fileToUpload As String = Dateipfad
    4. Dim fileLength As Long = My.Computer.FileSystem.GetFileInfo(fileToUpload).Length
    5. 'C: Next, get our URL and port, and then combine them if a port was provided.
    6. Dim url As String = Serverpfad
    7. Dim port As String = ConPort
    8. 'If the port was provided, then insert it into the url.
    9. If port <> "" Then
    10. 'Insert the port into the Url
    11. 'https://www.example.com:80/directory
    12. Dim u As New Uri(url)
    13. 'Get the host (example: www.example.com)
    14. Dim host As String = u.Host
    15. 'Replace the host with the host:port
    16. url = url.Replace(host, host & ":" & port)
    17. End If
    18. 'C: Add the name of the file we are uploading to the end of the url
    19. ' This creates a "target" file name
    20. url = url.TrimEnd("/"c) & "/" & IO.Path.GetFileName(fileToUpload)
    21. 'C: Request a stream from the WebDAV server for the file we want to upload.
    22. 'Create the request
    23. Dim request As HttpWebRequest =
    24. DirectCast(WebRequest.Create(url), HttpWebRequest)
    25. 'Set the User Name and Password
    26. request.Credentials = New NetworkCredential(Benutzername, Passwort)
    27. 'Let the server know we want to "put" a file on it
    28. request.Method = WebRequestMethods.Http.Put
    29. 'Set the length of the content (file) we are sending
    30. request.ContentLength = fileLength
    31. '*** This is required for our WebDav server ***
    32. request.SendChunked = True
    33. request.Headers.Add("Translate: f")
    34. request.AllowWriteStreamBuffering = True
    35. Dim s As IO.Stream = Nothing
    36. Try
    37. 'Send the request to the server, and get the
    38. ' server's (file) Stream in return.
    39. s = request.GetRequestStream()
    40. Catch ex As Exception
    41. If MeldungenZeigen = True Then
    42. Console.WriteLine(ex.Message)
    43. Console.WriteLine("")
    44. End If
    45. End Try
    46. 'C: After the server has given us a stream, we can begin to write to it.
    47. '
    48. ' Note: The data is not actually being sent to the server
    49. ' here, it is written to a stream in memory.
    50. ' The data is actually sent below when the Response is retrieved
    51. ' from the server.
    52. 'Open the file so we can read the data from it
    53. Dim fs As New IO.FileStream(fileToUpload, IO.FileMode.Open, IO.FileAccess.Read)
    54. 'Create the buffer for storing the bytes read from the file
    55. Dim byteTransferRate As Integer = 1024
    56. Dim bytes(byteTransferRate - 1) As Byte
    57. Dim bytesRead As Integer = 0
    58. Dim totalBytesRead As Long = 0
    59. 'Read from the file and write it to the server's stream.
    60. Do
    61. 'Read from the file
    62. bytesRead = fs.Read(bytes, 0, bytes.Length)
    63. If bytesRead > 0 Then
    64. totalBytesRead += bytesRead
    65. 'Write to stream
    66. s.Write(bytes, 0, bytesRead)
    67. End If
    68. Loop While bytesRead > 0
    69. 'Close the server stream
    70. s.Close()
    71. s.Dispose()
    72. s = Nothing
    73. 'Close the file
    74. fs.Close()
    75. fs.Dispose()
    76. fs = Nothing
    77. 'C: Although we have finished writing the file to the stream, the file
    78. ' has not been uploaded yet. If we exited here without continuing,
    79. ' the file would not be uploaded.
    80. 'C: Now we have to send the data to the server
    81. Dim response As HttpWebResponse = Nothing
    82. Try
    83. '*** Send the data to the server
    84. ' Note: When we get the response from the server, we
    85. ' are actually sending the data to the server, and receiving
    86. ' the server's response to it in return.
    87. '
    88. ' If we did not perform this step, the file would not be uploaded.
    89. response = DirectCast(request.GetResponse(), HttpWebResponse)
    90. 'C: Finally, after we have uploaded the file, perform a little
    91. ' validation just to make sure everything worked as expected.
    92. 'Get the StatusCode from the server's Response
    93. Dim code As HttpStatusCode = response.StatusCode
    94. 'Close the response
    95. response.Close()
    96. response = Nothing
    97. 'Validate the uploaded file:
    98. ' Check the totalBytesRead and the fileLength. Both must be an exact match.
    99. '
    100. ' Check the StatusCode from the server and make sure the file was "Created"
    101. ' Note: There are many different possible status codes. You can choose
    102. ' which ones you want to test for by looking at the "HttpStatusCode" enumerator.
    103. If totalBytesRead = fileLength AndAlso
    104. code = HttpStatusCode.Created Then
    105. If MeldungenZeigen = True Then
    106. Console.WriteLine("Die XML-Datei wurde erfolgreich hochgeladen!")
    107. Console.WriteLine("")
    108. End If
    109. Else
    110. If MeldungenZeigen = True Then
    111. Console.WriteLine("Es ist ein Fehler beim Upload der Datei aufgetreten")
    112. Console.WriteLine("")
    113. CMDVerzögertSchließen = True
    114. End If
    115. End If
    116. Return True
    117. Catch ex As Exception
    118. If MeldungenZeigen = True Then
    119. Console.WriteLine(ex.Message)
    120. Console.WriteLine("")
    121. End If
    122. Return False
    123. End Try
    124. End Function



    Würde mich über eure Hilfe freuen :)
    Der Vorteil der Intelligenz besteht darin, sich dumm stellen zu können. Das Gegenteil davon ist schon schwieriger.

    Yunkie schrieb:

    System.Net.http
    Gibt's das?
    Ich kenne nur System.Net.HttpWebRequest und der funktioniert auch bei neueren Frameworks.

    Ansonsten kannst du dir auch über nuget den WebDAV.Client laden.

    --
    If Not Program.isWorking Then Code.Debug Else Code.DoNotTouch
    --

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „petaod“ ()

    Okay,

    vielen Dank erstmal für eure Antworten! Ich muss gestehen, ich hab mich mit dem NuGet noch nie auseinander gesetzt.

    Aber das werde ich dann gleich mal nachholen.

    Danke nochmal!
    Der Vorteil der Intelligenz besteht darin, sich dumm stellen zu können. Das Gegenteil davon ist schon schwieriger.
    Moin,

    ich muss das Thema leider doch nochmal aufmachen.

    Ich bekomms einfach nicht gebacken... Ich hab jetzt per NuGet die beiden genannten Pakete installiert.

    Das
    ​nuget.org/packages/System.Net.Http/
    bringt leider nichts.

    Da bekomme ich immer folgenden Fehler:

    Spoiler anzeigen
    ​Die Verbindung mit dem Remoteserver kann nicht hergestellt werden.

    Unbehandelte Ausnahme: System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.
    bei ConsoleApplication1.Module1.XML_hochladen(String Dateipfad, String Serverpfad, String ConPort, String Benutzername, String Passwort)
    bei ConsoleApplication1.Module1.AblaufClientbetrieb()
    bei ConsoleApplication1.Module1.Main(String[] Paras)


    Netzwerk spielt hier keine Rolle. Der Kasten auf dem das Tool läuft hängt direkt am Internet und der WEBDav-Server ist erreichbar.


    Und wie ich den
    WebDAV.Client​
    nutzen kann finde ich nicht. Habt ihr da Beispiele?



    Danke nochmal!
    Der Vorteil der Intelligenz besteht darin, sich dumm stellen zu können. Das Gegenteil davon ist schon schwieriger.
    Ich versteh es nicht...

    Habe jetzt mal die Beispiele auf VB umgebogen... Dabei kam dies raus:

    VB.NET-Quellcode

    1. Public Async Function XML_hochladen(ByVal Dateipfad As String, ByVal Serverpfad As String, ByVal ConPort As String, ByVal Benutzername As String, ByVal Passwort As String) As Threading.Tasks.Task(Of Boolean)
    2. Dim WDParams As New WebDav.WebDavClientParams
    3. With WDParams
    4. .BaseAddress = New Uri(Serverpfad)
    5. .Credentials = New Net.NetworkCredential(Benutzername, Passwort)
    6. End With
    7. Using WD = New WebDav.WebDavClient(WDParams)
    8. Dim Respones As WebDav.WebDavResponse
    9. Respones = Await WD.PutFile(Split(Dateipfad, "\").Last, IO.File.OpenRead(Dateipfad))
    10. If MeldungenZeigen = True Then
    11. Console.WriteLine(Respones)
    12. End If
    13. End Using
    14. Return True
    15. End Function


    Durch das enthaltene "Await" macht er aus dem Rückgabewert der Funktion immer ein

    VB.NET-Quellcode

    1. Threading.Tasks.Task(of Boolean)

    Ich weiß nicht wie ich das verwursten muss.

    Ich möchte doch eigentlich nur eine Funktion, welcher ich die Parameter "Serverpfad" "Dateipfad" "Benutzername" und "Passwort" mitgebe und diese mir dann einen Boolean zurückgibt, der mir sagt "Datei hochgeladen" oder "Datei nicht hochgeladen"

    Warum muss das Asynchron laufen?
    Der Vorteil der Intelligenz besteht darin, sich dumm stellen zu können. Das Gegenteil davon ist schon schwieriger.

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „Yunkie“ ()

    OK, da es sich dabei um XML-Dateien handelt mit maximal 1MB groß sind und bei der das Hochladen selbst bei ISDN nicht sooo lange dauert ist es eigentlich nicht von Nöten.

    Aber wenn es die bevorzugte Arbeitsweise ist, passe ich mich dem an...

    Allerdings, weiß ich leider immer noch nicht, wie ich die obige Funktion zum laufen bekomme. Ich lese grade bei MS diesen Artikel aber steige trotzdem nicht dahinter.

    Kann mir einer meine Funktion anpassen/umbauen und kurz erläutern worauf dabei dann zu achten ist?

    Der Aufruf:

    VB.NET-Quellcode

    1. ​XML_hochladen(Dateipfad, "https://Irgendwas", "Benutzername", "Passwort")


    Die Funktion:

    VB.NET-Quellcode

    1. ​Public Async Function XML_hochladen(ByVal Dateipfad As String, ByVal Serverpfad As String, ByVal Benutzername As String, ByVal Passwort As String) As Threading.Tasks.Task(Of Boolean)
    2. Dim WDParams As New WebDav.WebDavClientParams
    3. With WDParams
    4. .BaseAddress = New Uri(Serverpfad)
    5. .Credentials = New Net.NetworkCredential(Benutzername, Passwort)
    6. End With
    7. Using WD = New WebDav.WebDavClient(WDParams)
    8. Dim Respones As WebDav.WebDavResponse
    9. Respones = Await WD.PutFile(Split(Dateipfad, "\").Last, IO.File.OpenRead(Dateipfad))
    10. End Using
    11. Return True
    12. End Function


    Danke!
    Der Vorteil der Intelligenz besteht darin, sich dumm stellen zu können. Das Gegenteil davon ist schon schwieriger.