none
Check if file still exists RRS feed

  • Question

  • I'm basically making a DLL injector (I hope I'm not getting banned from forums for making such programs) and I was wondering how to check if a file still exists.

    Here's my injector. You must fill in a process and then browse for DLL's to inject. Now, if a DLL is added to the listbox and the user clicks on 'INJECT', the file will be injected into the process. But my problem is: I want to check if the file that has been added to the listbox, still exists when the user clicks on 'INJECT'. If the file was moved or deleted while it's still in the listbox, it cannot be injected of course, so I want to throw an error message. I've seen the If File.Exists function but I can't use that because I must insert a string and I want it to be for all the files inside the listbox.

    Thursday, December 27, 2012 7:48 PM

Answers

  • I haven't included code that uses the .Exists method because I'm sure (like you said) it will check if the filename is in the listbox and will therefor always return true. I want it to be able to check for the full file path, but that's something I can't. This is what this thread is about. I'm not posting an error, but I'm asking for some help with code. I hope you can give me the code to check the full file path and check if the file is still there.

    I'll show you using a different scenario and a different control, but the idea is the same. This isn't the only way, but it's one way:

    Option Strict On Option Explicit On ' Imports System.IO.Path ' Public Class Form1 ' Private Class MyFileInfo Public NameToDisplay As String = "--" Public FullPath As String = "--" Public FileSize_Bytes As Long Public FileSize_String As String = "--" End Class ' Private mfiList As New List(Of MyFileInfo) ' Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles MyBase.Load ' With ListView1 .Columns.Add("File Name", 200, HorizontalAlignment.Left) .Columns.Add("File Size", 100, HorizontalAlignment.Left) .FullRowSelect = True .GridLines = True .MultiSelect = False .View = View.Details End With ' btn_RemoveFile.Enabled = False btn_DisplayFileInfo.Enabled = False ' End Sub ' Private Sub ListView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles ListView1.SelectedIndexChanged ' If ListView1.SelectedItems.Count = 1 Then btn_RemoveFile.Enabled = True btn_DisplayFileInfo.Enabled = True Else btn_RemoveFile.Enabled = False btn_DisplayFileInfo.Enabled = False End If ' End Sub ' Private Sub btn_AddFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btn_AddFile.Click ' Using ofd As New OpenFileDialog With ofd .AddExtension = False .CheckFileExists = True .CheckPathExists = True .Filter = "All Files (*.*)|*.*" .FilterIndex = 1 .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments .Multiselect = True .Title = "Select One Or More Files" End With ' If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then For Each f As String In ofd.FileNames Dim okToAdd As Boolean = True Dim showName As String = GetFileNameWithoutExtension(f) ' Dim qry = From mfi As MyFileInfo In mfiList _ Where mfi.NameToDisplay = showName ' If qry.Count > 0 Then okToAdd = False End If ' If okToAdd Then Dim thisMFI As New MyFileInfo ' With thisMFI .NameToDisplay = showName .FullPath = f .FileSize_Bytes = My.Computer.FileSystem.GetFileInfo(f).Length .FileSize_String = ShowTotalFileSize(.FileSize_Bytes) End With ' mfiList.Add(thisMFI) End If Next ' UpdateListView() End If End Using ' End Sub ' Private Sub btn_RemoveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btn_RemoveFile.Click ' If ListView1.SelectedItems.Count = 1 Then ListView1.BeginUpdate() ' Dim lvi As ListViewItem = ListView1.SelectedItems(0) ListView1.Items.Remove(lvi) ' ListView1.EndUpdate() End If ' End Sub ' Private Sub btn_DisplayFileInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btn_DisplayFileInfo.Click ' If ListView1.SelectedItems.Count = 1 Then Dim lvi As ListViewItem = ListView1.SelectedItems(0) Dim displayName As String = lvi.Text ' Dim qry = From mfi As MyFileInfo In mfiList _ Where mfi.NameToDisplay = displayName ' If qry.Count = 1 Then Dim sb As New System.Text.StringBuilder sb.AppendLine("File Name: " & GetFileName(qry.First.FullPath)) sb.AppendLine("Full Path: " & qry.First.FullPath) sb.AppendLine("File Size (Bytes): " & qry.First.FileSize_Bytes.ToString("n0")) sb.AppendLine("File Size (String): " & qry.First.FileSize_String) ' MessageBox.Show(sb.ToString, "Information On Selected File", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End If End If ' End Sub ' Private Sub UpdateListView() ' Dim qry = From mfi As MyFileInfo In mfiList _ Order By mfi.NameToDisplay ' With ListView1 .BeginUpdate() .Items.Clear() ' For Each mfi As MyFileInfo In qry Dim lvItem As New ListViewItem(mfi.NameToDisplay, 0) lvItem.SubItems.Add(mfi.FileSize_String) ListView1.Items.AddRange(New ListViewItem() {lvItem}) Next ' .EndUpdate() End With ' End Sub ' Private Function ShowTotalFileSize(ByVal bytes As Long) As String ' Dim stringToReturn As String = "" ' If bytes < 1024 Then stringToReturn = bytes.ToString("n1") & " bytes" ElseIf bytes < (1024 * 1024) Then stringToReturn = (bytes / 1024).ToString("n0") & " kB" ElseIf bytes >= (1024 * 1024) And bytes < (1024 * 1024 * 1024) Then stringToReturn = (bytes / (1024 * 1024)).ToString("n1") & " Megs" ElseIf bytes >= (1024 * 1024 * 1024) Then stringToReturn = (bytes / (1024 * 1024 * 1024)).ToString("n2") & " Gigs" End If ' Return stringToReturn ' End Function ' End Class


    The idea is this: Don't use a control (any control) for storage of data; use something more appropriate. In this one I created a class with a few fields then I used a List(T) of that class to hold each instance of which is created when the user selects a file to add.

    Note that in this I used LINQ in several places, but you can use a more conventional approach if you're more at ease with that sort of thing.

    One caveat about what I have here is that you can't have more than one file whose name (without the extension) resolves to the same thing as another file which is in the list. The reason being because that's what's used to identify "they want THIS file" in query to locate the file information.

    You could easily extend that to do something simple like checking for the existence of that particular file by referencing its full path.


    Please call me Frank :)

    Saturday, December 29, 2012 2:27 PM
  • I haven't included code that uses the .Exists method because I'm sure (like you said) it will check if the filename is in the listbox and will therefor always return true. I want it to be able to check for the full file path, but that's something I can't. This is what this thread is about.

    You can edit your posts to remove the references to the purpose of your application, as it has nothing to do with your problem.

    The .Contains method can be used with a collection, such as the listbox Items collection, to determine whether or not a particular item is in the collection.  The .Exists method, on the other habd, is used with a single string to determine whether the file eists or not.  It does not check if the filename is in the listbox.  You might use it to check on the currently selected listbox item, or you could cycle thorugh the list box Items collection and test all items. For instance:

    For Each FileName As String in ListBox1.Items
        If Not File.Exists(FileName) Then 'deal with it

    If the problem is that you are not recording the full file path and name in the list box then you need to adjust this line:

                  ListBox1.Items.Add(DllFileName)

    so that the full path is recorded.  Or, maintain a separate list of complete path names as your primary reference, and simply build the list box as a display of filenames from that primary source.

    Monday, December 31, 2012 9:18 PM

All replies

  • I doubt that you will get any help or advice here, what you are trying to do is considered malicious code.
    Thursday, December 27, 2012 10:14 PM
  • I've seen the If File.Exists function but I can't use that because I must insert a string

    That bit doesn't make sense to me.  The Exists method takes a string as the argument and returns a result that indicates whether or not the file referred to by that string value exists.  That seems to be exactly what you are after.  Why do you believe that there is a problem inserting a string?

    ... and I want it to be for all the files inside the listbox.

    Loop thgrough the files in the list and test them one at a time.

    Thursday, December 27, 2012 10:40 PM
  • Can you help me with some code? I'm really just a noobie... Let's say there are 3 DLL files listed in the box and I want to check for all 3 if they still exist.

    Also, I want to say that I'm not looking for a check if the file is in the listbox, I want to check if the file is still on the hard drive (if it isn't deleted). Because the user has to add items with an OpenFileDialog.
    • Edited by Rionto Friday, December 28, 2012 10:28 AM
    Friday, December 28, 2012 10:15 AM
  • Can you help me with some code? I'm really just a noobie... 

    You are a newbie and are able to inject DLL assemblies. 

    Strange, what do you mean with inject?


    Success
    Cor

    Friday, December 28, 2012 10:34 AM
  • You will need to explain your problem a little more clearly.   The listbox Items collection contains the filenames as strings.  The description for the Exists method shows how to use a string as an argument and test the result.  You sinply repeat the test for as many items as there are in the collection.  If this is not working for you, then show the code you are using and describe the exact difficulty that you are having.

    http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.items(v=vs.100).aspx

    http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection(v=vs.100).aspx

    http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.100).aspx

    Friday, December 28, 2012 10:46 AM
  • I know how to check if a file is in the listbox, but just not how to check if the file is still on the hard disk. So, in the program you have to select a DLL file that's on your computer. The file will then be added to the listbox (not really the file itself, but it will be added as a string). Here's the code of my OpenFileDialog to explain this a little bit better:

        Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
            Dim FileName As String = OpenFileDialog1.FileName.Substring(OpenFileDialog1.FileName.LastIndexOf("\"))
            Dim DllFileName As String = FileName.Replace("\", "")
            If ListBox1.Items.Contains(DllFileName) Then
                MsgBox("A DLL with the same name already exists!")
            Else
                ListBox1.Items.Add(DllFileName)
                dlls.Add(DllFileName, OpenFileDialog1.FileName)
            End If
        End Sub

    I don't want to check if the string is in the listbox, but if the file (that corresponds to the string) is still on the drive. Because the program must use the file itself to inject it into a process and if that file is lost, it can't, so I want to throw an error.

    I basically want something like: search the listbox for strings and if there is a string, look to which file the string is related, then look if that file exists.

    Friday, December 28, 2012 1:50 PM
  • I am! I just searched the net for some code that was able to do that. And I'll explain the 'inject part'. An injector, like I am making, is to inject DLL's into a process. Mostly the DLL would be some kind of aimbot and the process would be a shooter game. That means you can use the aimbot in the game, because the DLL was 'added' to the game. The game handles the DLL as part of the game, because it was loaded into it. I don't know if I'm really clear and if my information is true but it's the best I could do...

    Friday, December 28, 2012 1:55 PM
  • Cor:

    DLL injection is a technique used for running code within the address space of another process by forcing it to load a dynamic-link library that the original creators of the process did not intend to be part of their program. That is why I made the original comment that I posted. As far as I know, injection is used for cheating on games and making trojans/viruses. This whole story seems strange as you said, a newbie that doesn't know how to tell if a file exists, but is making code to inject DLL's.

    Friday, December 28, 2012 8:56 PM
  • You haven't included any code that uses the listbox items and uses the .Exists method, so I can't tell what the problem you are having might be.  The code you have provided is part of the process of loading the list box items, but you have stated that you need to check the listbox items at some stage after that, because the file might have been removed since it was added.

    You need to show the code where you are looping through the list box items collection and using each string in that collection in the .Exists method in order for people to understand the problem that you are trying to solve.  For instance, if the .Exists method is always returning False then it might be becasue you are adding just the filename to the listbox, when you should be adding the full file path?

    Note that it is not a good idea to be using the listbox as your data source.  When the user selects a file to be added, you should add that selection to a list of the correct type (for instance, File).  The list box can then be created as the string values (filenames) for that type for the purpose of display.  In this case, however, the difference would be slight.

    Friday, December 28, 2012 9:08 PM
  • Rionto,

    I’ve stayed clear of this thread for the same reason that [I feel sure] many other members here have: Because of your stated purpose.

    Don’t get me wrong, what you’re asking is, in and of itself, certainly not something that’s malevolent (so why did you even bring up what it’s being used for?). Acamar is exactly right I might add, but I will caution you:

    Please do not post any code which demonstrates .dll injection.

    I hope that you’ll take heed to my suggestion and truly I do hope that you find resolution, but I caution you – strongly – NOT to post code which could be used for malicious purpose, despite what your intended use is.


    Please call me Frank :)

    Friday, December 28, 2012 9:38 PM
  • You need to show the code where you are looping through the list box items collection and using each string in that collection in the .Exists method in order for people to understand the problem that you are trying to solve.  For instance, if the .Exists method is always returning False then it might be becasue you are adding just the filename to the listbox, when you should be adding the full file path?


    I haven't included code that uses the .Exists method because I'm sure (like you said) it will check if the filename is in the listbox and will therefor always return true. I want it to be able to check for the full file path, but that's something I can't. This is what this thread is about. I'm not posting an error, but I'm asking for some help with code. I hope you can give me the code to check the full file path and check if the file is still there.
    Saturday, December 29, 2012 10:52 AM
  • I knew it was a bit risky to post this here, but since there is no way -for as long as I know- to delete this thread and I'm not actually posting or requesting for .dll injection code, I am going to keep looking for an answer. It's just that I want to check for a file's existence. I brought up the injector to make it clear what my problem is. Again, I will not post any code that can be used for malicious purposes.

    Saturday, December 29, 2012 10:58 AM
  • You are totally right, except I won't use this for making viruses. I'm using it so that users can cheat in games.
    Saturday, December 29, 2012 10:59 AM
  • I haven't included code that uses the .Exists method because I'm sure (like you said) it will check if the filename is in the listbox and will therefor always return true. I want it to be able to check for the full file path, but that's something I can't. This is what this thread is about. I'm not posting an error, but I'm asking for some help with code. I hope you can give me the code to check the full file path and check if the file is still there.

    I'll show you using a different scenario and a different control, but the idea is the same. This isn't the only way, but it's one way:

    Option Strict On Option Explicit On ' Imports System.IO.Path ' Public Class Form1 ' Private Class MyFileInfo Public NameToDisplay As String = "--" Public FullPath As String = "--" Public FileSize_Bytes As Long Public FileSize_String As String = "--" End Class ' Private mfiList As New List(Of MyFileInfo) ' Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles MyBase.Load ' With ListView1 .Columns.Add("File Name", 200, HorizontalAlignment.Left) .Columns.Add("File Size", 100, HorizontalAlignment.Left) .FullRowSelect = True .GridLines = True .MultiSelect = False .View = View.Details End With ' btn_RemoveFile.Enabled = False btn_DisplayFileInfo.Enabled = False ' End Sub ' Private Sub ListView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles ListView1.SelectedIndexChanged ' If ListView1.SelectedItems.Count = 1 Then btn_RemoveFile.Enabled = True btn_DisplayFileInfo.Enabled = True Else btn_RemoveFile.Enabled = False btn_DisplayFileInfo.Enabled = False End If ' End Sub ' Private Sub btn_AddFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btn_AddFile.Click ' Using ofd As New OpenFileDialog With ofd .AddExtension = False .CheckFileExists = True .CheckPathExists = True .Filter = "All Files (*.*)|*.*" .FilterIndex = 1 .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments .Multiselect = True .Title = "Select One Or More Files" End With ' If ofd.ShowDialog = Windows.Forms.DialogResult.OK Then For Each f As String In ofd.FileNames Dim okToAdd As Boolean = True Dim showName As String = GetFileNameWithoutExtension(f) ' Dim qry = From mfi As MyFileInfo In mfiList _ Where mfi.NameToDisplay = showName ' If qry.Count > 0 Then okToAdd = False End If ' If okToAdd Then Dim thisMFI As New MyFileInfo ' With thisMFI .NameToDisplay = showName .FullPath = f .FileSize_Bytes = My.Computer.FileSystem.GetFileInfo(f).Length .FileSize_String = ShowTotalFileSize(.FileSize_Bytes) End With ' mfiList.Add(thisMFI) End If Next ' UpdateListView() End If End Using ' End Sub ' Private Sub btn_RemoveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btn_RemoveFile.Click ' If ListView1.SelectedItems.Count = 1 Then ListView1.BeginUpdate() ' Dim lvi As ListViewItem = ListView1.SelectedItems(0) ListView1.Items.Remove(lvi) ' ListView1.EndUpdate() End If ' End Sub ' Private Sub btn_DisplayFileInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btn_DisplayFileInfo.Click ' If ListView1.SelectedItems.Count = 1 Then Dim lvi As ListViewItem = ListView1.SelectedItems(0) Dim displayName As String = lvi.Text ' Dim qry = From mfi As MyFileInfo In mfiList _ Where mfi.NameToDisplay = displayName ' If qry.Count = 1 Then Dim sb As New System.Text.StringBuilder sb.AppendLine("File Name: " & GetFileName(qry.First.FullPath)) sb.AppendLine("Full Path: " & qry.First.FullPath) sb.AppendLine("File Size (Bytes): " & qry.First.FileSize_Bytes.ToString("n0")) sb.AppendLine("File Size (String): " & qry.First.FileSize_String) ' MessageBox.Show(sb.ToString, "Information On Selected File", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End If End If ' End Sub ' Private Sub UpdateListView() ' Dim qry = From mfi As MyFileInfo In mfiList _ Order By mfi.NameToDisplay ' With ListView1 .BeginUpdate() .Items.Clear() ' For Each mfi As MyFileInfo In qry Dim lvItem As New ListViewItem(mfi.NameToDisplay, 0) lvItem.SubItems.Add(mfi.FileSize_String) ListView1.Items.AddRange(New ListViewItem() {lvItem}) Next ' .EndUpdate() End With ' End Sub ' Private Function ShowTotalFileSize(ByVal bytes As Long) As String ' Dim stringToReturn As String = "" ' If bytes < 1024 Then stringToReturn = bytes.ToString("n1") & " bytes" ElseIf bytes < (1024 * 1024) Then stringToReturn = (bytes / 1024).ToString("n0") & " kB" ElseIf bytes >= (1024 * 1024) And bytes < (1024 * 1024 * 1024) Then stringToReturn = (bytes / (1024 * 1024)).ToString("n1") & " Megs" ElseIf bytes >= (1024 * 1024 * 1024) Then stringToReturn = (bytes / (1024 * 1024 * 1024)).ToString("n2") & " Gigs" End If ' Return stringToReturn ' End Function ' End Class


    The idea is this: Don't use a control (any control) for storage of data; use something more appropriate. In this one I created a class with a few fields then I used a List(T) of that class to hold each instance of which is created when the user selects a file to add.

    Note that in this I used LINQ in several places, but you can use a more conventional approach if you're more at ease with that sort of thing.

    One caveat about what I have here is that you can't have more than one file whose name (without the extension) resolves to the same thing as another file which is in the list. The reason being because that's what's used to identify "they want THIS file" in query to locate the file information.

    You could easily extend that to do something simple like checking for the existence of that particular file by referencing its full path.


    Please call me Frank :)

    Saturday, December 29, 2012 2:27 PM
  • I haven't included code that uses the .Exists method because I'm sure (like you said) it will check if the filename is in the listbox and will therefor always return true. I want it to be able to check for the full file path, but that's something I can't. This is what this thread is about.

    You can edit your posts to remove the references to the purpose of your application, as it has nothing to do with your problem.

    The .Contains method can be used with a collection, such as the listbox Items collection, to determine whether or not a particular item is in the collection.  The .Exists method, on the other habd, is used with a single string to determine whether the file eists or not.  It does not check if the filename is in the listbox.  You might use it to check on the currently selected listbox item, or you could cycle thorugh the list box Items collection and test all items. For instance:

    For Each FileName As String in ListBox1.Items
        If Not File.Exists(FileName) Then 'deal with it

    If the problem is that you are not recording the full file path and name in the list box then you need to adjust this line:

                  ListBox1.Items.Add(DllFileName)

    so that the full path is recorded.  Or, maintain a separate list of complete path names as your primary reference, and simply build the list box as a display of filenames from that primary source.

    Monday, December 31, 2012 9:18 PM