Deleting a file located in root directory with FtpWebRequest method - vb.net

I'm facing a problem while implementing some FTP operation in a small tool (windows form) for data management on several FTP servers. Basically I need to connect to a list of ftp://xxx.xxx.xxx.xxx servers with credentials, look for any *.csv file available, download it to local hard disk and then delete it on ftp server.
I did most of the job like following:
Created a loop for connecting on all ftp server in the list
For each connection, get the file list, download each file of the list and delete it from the server
My problem is that the Delete Sub I created give me a 550 exception (not regular file). Looking deep it seems that is try to delete "/filename.csv" instead of "filename.csv", so that is the reason for the error.
I think this is related to the fact that the file is in the root directory and the URI that I pass as argument for the ftpwebrequest is in the form of "ftp://xxx.xxx.xxx.xxx/filename.csv", but I don't know other ways to get around this.
Can anybody give me a tip?
Thanks
EDIT: I'm thinking that maybe sending a "cd /" command before requesting the delete could solve the situation, but I don't know how to implement it inside the FTP_Delete function. Any ideas? Thanks
Sub FTP_Delete(filename As String, ftp_adress As String, user As String, password As String)
FileFullPath = ftp_adress & "/" & filename
'Create Request To Delete File'
Dim wrDelete As FtpWebRequest = CType(WebRequest.Create(FileFullPath), FtpWebRequest)
'Specify That You Want To Delete A File'
wrDelete.Method = WebRequestMethods.Ftp.DeleteFile
'Specify Username & Password'
wrDelete.Credentials = New NetworkCredential(user, password)
'Response Object'
Dim rDeleteResponse As FtpWebResponse
Try
rDeleteResponse = CType(wrDelete.GetResponse(), FtpWebResponse) ' ** Eccezione
Catch errore As WebException
rDeleteResponse = DirectCast(errore.Response, FtpWebResponse)
Me.UpdateHistory("Delete Error: " & rDeleteResponse.StatusCode & "-" & rDeleteResponse.StatusDescription)
End Try
'Close'
rDeleteResponse.Close()
End Sub

Related

Cannot find who has file open

I have this code that find who has a file opened. The files are on network drives that use our old username as authenication. Our username use to be john.doe, it is now a number 12345. The code does not find a username. Is there something I'm overlooking or need to do to find out who has the file opened? Curious if and when we are on the actual new network that host the username 12345, that we will be able to find see the username 12345. The error message i do get is:
"The trust relationship between this workstation and the primary domain failed"
Public Shared Function GetFileOwner(ByVal strFileName)
Try
Dim objSD As Object = Nothing
Dim objWMIService = GetObject("winmgmts:")
Dim objFileSecuritySettings =
objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strFileName & "'")
Dim intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
If intRetVal = 0 Then
GetFileOwner = objSD.Owner.Name
Else
GetFileOwner = "Unknown"
End If
Catch ex As Exception
MsgBox("Error :" & Date.Today.ToString & " " & ex.Message)
GetFileOwner = "Unknown"
End Try
End Function
Do you know that this option is available on your server? You can easily do this..
Open the Computer Management snap-in on your file server (or connect to the server remotely from the management console running on your computer) and go to System Tools -> Shared Folders -> Open files. The list of files opened on the remote server is displayed on the right side of the window.
Many times i tried to access my server on the domain and it gave me that error, domains hate custom made apps :)

Why GetFiles from a remote folder using Linq is hanging

I'm trying to fetch the files inside a folder ordered by LastWriteTime.
The code is running very fast when accessing to a local path (C:\MyFolder), but is hanging when accessing to a remote path (\\MyServer\MyFolder)
Dim myOrderedList As List(Of String) = (From item In IO.Directory.GetFiles(strFolderSource) _
Let file = New IO.FileInfo(item) _
Order By file.LastWriteTime _
Select item).ToList()
Should this code work? Is not allowed this method to get files from a remote folder?
Which alternative code could I use to get the same result without hanging?
EDITED (2019-01-18 16:32):
Sorry guys, I've tried the proposed solution from Rango, and still the same hang. Finally I created a small logging system to catch the step that caused the problem, and realized that all is a credential problem.
Just before the code I posted I do a NET USE to grant access to the remote computer, and the net use is executed, but for any reason, the GetFiles() fails because of Logon failure: unknown user name or bad password.
So, Could I ensure the credentials with the net use before call the GetFiles()?
Maybe using a pause or something like this?
FULL CODE:
Dim processInfo As New System.Diagnostics.ProcessStartInfo()
processInfo.FileName = "C:\WINDOWS\system32\net"
processInfo.Arguments = "net use \\MyServer\IPC$ ""password"" /USER:Username"
System.Diagnostics.Process.Start(processInfo)
Dim myOrderedList As List(Of String) = (From item In IO.Directory.GetFiles("\\MyServer\g$\MyFolder") _
Let file = New IO.FileInfo(item) _
Order By file.LastWriteTime _
Select item).ToList()
You could try to use DirectoryInfo.EnumerateFiles instead wich has two advantages:
No consecutive security handshakes from the remote server necessary
Streaming the files instead of loading all into memory before you start ordering them
Dim di = new DirectoryInfo(strFolderSource)
Dim files = From fi In di.EnumerateFiles() Order By fi.LastWriteTime Select fi.FullName
Dim myOrderedList As List(Of String) = files.ToList()
Finally solved including a sleep of 5 seconds after the net use and before the GetFiles():
System.Threading.Thread.Sleep(5000)
Thanks for your time, and hope this helps anybody with a similar problem.

Delete .txt file with vb.net

i have an application that create a txt file and write in it a log.
I create the txt file with the following code:
If System.IO.File.Exists(sFileName) = True Then
System.IO.File.Delete(sFileName)
End If
'System.IO.File.Create(sFileName) '.dispose
Dim objWriter As New System.IO.StreamWriter(sFileName, True)
When i finish to write the log (using objWriter.WriteLine) and close it (objwriter.close and objwriter.dispose), send it by mail and need to delete it.
In order to delete the file i use this code:
For i = 0 To 10
Try
'System.IO.File.Delete(sFileName)
'My.Computer.FileSystem.DeleteFile(sFileName, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
My.Computer.FileSystem.DeleteFile(sFileName)
Exit For
Catch ex As Exception
If i = 10 Then
invioMailTest(ex.ToString)
End If
Threading.Thread.Sleep(1000)
End Try
Next
The code works well in local, but when i run it on the server (as administrator) it gives me the following error:
System.IO.IOException: The process cannot access the file 'C:\Log_Eventi\Export log 2016-04-13.txt' because it is being used by another process.
i don't know how to delete it and i'm losing too much time on it....
When you create your file I'm guessing you are using
System.IO.File.Create(sFileName)
You can overcome that problem by using this code:
Using File.Create(sFileName)
End Using
put all code that deals with sFileName within Using.
other solutions:
use Close when you create it
System.IO.File.Create(sFileName).Close()
use filestream
Dim fs As FileStream = File.Create(sFileName)
do your work here
fs.Close()
You mention "send it by mail", so the problem is likely that the attachment is still being held by the server's email system.

How to delete all text in a text file on ftp server without deleting file itself in vb.net

Hi I am doing a chat orientated program in vb.net. I have everything working nicely but there is a feature I am trying to add where if the user types /clear it will then delete the chat text from the file, (the chat is an ftp connection and it writes to a text file)
i'm hoping to only delete text from the file not the whole file itself, i have tried appending but that as you probably know already just writes extra text to the file.
If anyone can help it would be great cheers :D
The way to go should be upload a new empty file overwriting the one on the FTP, with the same filename and path.
Dim wcFTP As New WebClient()
'wcFTP.Proxy = ...
wcFTP.BaseAddress = "ftp://foobar.domain.com"
wcFTP.Credentials = New NetworkCredential("user", "pass")
Dim sFilePath As String '= ...
Dim sFtpPath As String = wcFTP.BaseAddress & sFolder & Path.GetFileName(sFilePath)
wcFTP.UploadFile(sFtpPath, sFilePath)
Where sFilePath is the path of the empty file with the same name as the one in the server.
To get an empty file you can donwload and empty the file on the ftp, or simply create a new file with the same name and no data. For example:
Dim sFilePath As String = "C:\Folder\fileName.xml"
File.Create(sFilePath).Dispose()

Appending lines to a text file on an FTP server

I am making a simple hangman game as a school project, I thought it would be a good idea if players were able to submit words for other players to attempt to guess. I am required to use Visual Basic 2008 for this project.
I was wondering if there was any way to append a line to an existing text file on an FTP server. And if possible a way to edit existing lines.
For example I want to be able to submit lines in the format of:
Word;Submitter;CorrectGuesses;IncorrectGuesses
And also be able to check if the file contains a line where Word = Word And Submitter = Submitter, so that I can add 1 to either the number of correct or incorrect guesses of the word.
Thank you in advance for any help you can give me.
File unavailable (e.g., file not found, no access).
This happens if the file not exists yet.
So, let's create the file if it's not existing:
Dim str As String = "string to upload"
Dim vmx As String = ""
Try
vmx = wc.DownloadString("ftp://your-url/file.txt") & vbNewLine
Catch
wc.UploadString("ftp://your-url/file.txt", "")
vmx = ""
End Try
wc.UploadString("ftp://your-url/file.txt", vmx & str)
Add line to existing File
Add this to the top:
Imports System.Net
Connect to the FTP server:
Dim wc As New WebClient
wc.Credientals = New NetworkCrediental("FTP-USERNAME", "FTP-PASSWORD")
Upload string:
Dim str As String = "upload string"
wc.UploadString("ftp://.....com/datei.txt", wc.DownloadString("ftp://.....com/datei.txt" & vbNewLine & str)