Downloading a file from a remote server with network credentials

by Admin 6/9/2008 12:44:00 AM

Man, was this a pain in the butt.  Seems like downloading a file from a remote PC would be easy, but 'taint.  This worked great for me,  your mileage may vary.

   1:  'First we set up all of the filenames and locations, making heavy use of app.config.
   2:  Dim filename As String = String.Format("{0}-{1}-{2}.txt", CDate(checkDate).Year.ToString, CDate(checkDate).Month.ToString, CDate(checkDate).Day.ToString + 1)
   3:  Dim RemoteFile As String = String.Format("\\{0}\{1}\{2}", My.Settings.IpNumber, My.Settings.LogDirectory, filename)
   4:  Dim LocalDirectory As String = String.Format("{0}logs\", My.Settings.ReportLocation)
   5:  Dim LocalFile As String = String.Format("{0}{1}", LocalDirectory, filename)
   6:  'Hey, check for the localdirectory
   7:  If Not Directory.Exists(LocalDirectory) Then
   8:    Directory.CreateDirectory(LocalDirectory)
   9:  End If
  10:  'Then we set up a little security
  11:  Dim myClient As New System.Net.WebClient
  12:  Dim myCreds As New System.Net.NetworkCredential(My.Settings.Username, My.Settings.Password)
  13:  'Log the fact that we are starting.
  14:  My.Application.Log.WriteEntry(String.Format("Starting download of file {0}", fileName))
  15:  'Set up the securit
  16:  myClient.Credentials = myCreds
  17:  'Now we actually try and get the file.
  18:  Try
  19:    myClient.DownloadFile(RemoteFile, LocalFile)
  20:  Catch uae As System.UnauthorizedAccessException
  21:    My.Computer.FileSystem.WriteAllText(LocalFile, String.Format("The file path to file {0} was not available at the time of this posting.", file), True)
  22:  Catch ex As Exception
  23:    My.Application.Log.WriteException(ex)
  24:  End Try
  25:  My.Application.Log.WriteEntry(String.Format("Finished download of file {0}", fileName)) 
  26:   

 

Did this as part of a project at Wendy's.  Part of the Classic Posts collection.  (heh)

Tags:

Biz | VB

Comments are closed

About the author

Bill Sempf Bill Sempf
Author of C# All In One for Dummies (among other things)

E-mail me Send mail

Calendar

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Pages

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Sign in