0

This is my first question on the site and I am fairy new at how code works. I need to be able to open a file from a list view. I can get the file path to open up my file explorer, but can not get it to directly open the selected file. It gives me an error saying "System.ComponentModel.Win32Exception: 'The system cannot find the file specified" I've checked the file path from my file explorer and the path it pulls from and they both seem to match. Here is an example of what I've written.

Private Sub ListView1_Function(sender As Object, e As EventArgs) Handles ListView1.ItemSelectionChanged
    If Not ListView1.SelectedItems.Item(0).Text = "" Then
        For Each ListViewItemVar As ListViewItem In ListView1.Items
            Dim filePath As String = $"C:\Users\{My.User.Name.Split("\").ElementAt(1)}\S & J Tube Inc\Files_Storage - Documents\Shipping Wizard\"
            Dim selectedFile As String = ListViewItemVar.Text
            If ListViewItemVar.Selected = True Then
                If MessageBox.Show("You are about to open " & filePath & ".  Are you sure?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then
                Process.Start(filePath + selectedFile)
                ElseIf DialogResult.No Then
                    MsgBox("You decided not to open the file.")
                End If
            End If
        Next
    End If
End Sub
Jose Caro
  • 3
  • 2
  • I forgot to mention the files I want to open are all .txt files. – Jose Caro Jan 22 '20 at 17:11
  • When asking a question, please first say what your platform is? – Ms workaholic Jan 22 '20 at 17:12
  • 1
    @Msworkaholic the targetframework is .NET Framework 4.7.2 and the application type is Windows Form Applications. I plan on using this on Window workstations and surface tablets. – Jose Caro Jan 22 '20 at 17:21
  • 1
    Here is how you actually combine path and filename: `Process.Start(Path.Combine(filePath, selectedFile))`. The `+` operator is for adding numbers in vb.net, not joining strings. – djv Jan 22 '20 at 17:34
  • 1
    @djv - you can use + to concatenate, but it's not usually the preferred way because it can lead to issues. – TechGnome Jan 22 '20 at 17:38
  • 1
    @TechGnome no kidding. But when *should* you use it to combine strings? – djv Jan 22 '20 at 17:39
  • @JoseCaro - I think your problem is the concatenation, but not for the reasons stated previously. instead of ` Process.Start(filePath + selectedFile)` ... use the `system.io.path.combine` function instead: `Process.Start(system.io.path.combine(filePath, selectedFile))` actually anytime you're concatenating paths together, you should use the combine function as it'll ensure that the string will be built correctly with the proper slashes and whatnots. – TechGnome Jan 22 '20 at 17:41
  • 1
    @TechGnome right, what I said. – djv Jan 22 '20 at 17:42
  • @djv - in VB... never... in C#, always. ;) The + operator was expanded to include strings (if I remember right) to help with parity between VB & C#... again, it's one of those things, you can, but doesn't mean you should. – TechGnome Jan 22 '20 at 17:43
  • 2
    See [VB.NET string concatenation](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/operators-and-expressions/concatenation-operators), and [this answer](https://stackoverflow.com/a/734631/832052). BTW, `+` is a remnant from VB6, which predates C# by a long time. – djv Jan 22 '20 at 17:58
  • @TechGnome I understand that now thank you for explaining that to me, self teaching is a little difficult at times and especially when its something brand new. I have also tried using a file.openread then it throws "Illegal characters in path" along with the ways you both mentioned above. I don't see any illegal characters ( * " < >) etc.. – Jose Caro Jan 22 '20 at 18:44
  • 1
    Use `Environment.UserName` to get the current User name alone, instead of that weird thing with `My.User.Name`. Then use `Path.Combine()` to build a path, as djv already mentioned. Btw, why didn't you store the file full path (or a FileInfo object) in the first place? – Jimi Jan 22 '20 at 19:13
  • In looking at things a bit more closely, I wonder if this `S & J Tube Inc\Files_Storage - Documents` is the problem... @JoseCaro - can you retry this, but with a path with no spaces and no "special" characters? If that works, then the above segment of the path is the issue... you may need to quot escape them: `...""S & J Tube Inc""\""Files_Storage - Documents""...` – TechGnome Jan 22 '20 at 21:08
  • @TechGnome This file path content is being shared with my sites on SharePoint via onedrive sync could that cause an issue? – Jose Caro Jan 22 '20 at 21:29
  • @JoseCaro - I don't think so... It shouldn't. the files are still local... OneDrvie is just a service that runs in the background to sync the files. As far as VB should be concerned, it's just a normal local file. I think the spaces and/or the ampersand that's the issue, and should be perfectly easy to test out. – TechGnome Jan 22 '20 at 21:47
  • Please show the code that put the file names into the list view in the first place – Caius Jard Jan 22 '20 at 23:11

1 Answers1

0

You have to use ListView1_ItemActivate 1.Create a project with Form with ListView1 and Label1 controls on it 2.Replace yourName in dirInfo with your name from Users\eee\Documents And all the code you need is :

Imports System.IO
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'CreateHeadersAndFillListView
    ListView1.View = View.Details
    ListView1.Columns.Add("Filename") 
    ListView1.Columns.Add("Size") 
    ListView1.Columns.Add("Last accessed") 

    Dim dirInfo As New DirectoryInfo("C:\Users\yourName\Documents")
    Dim fileInfo As FileInfo

    Dim lvi As ListViewItem
    Dim lvsi As ListViewItem.ListViewSubItem

    For Each fileInfo In dirInfo.GetFiles("*.*")
        lvi = New ListViewItem With {
            .Text = fileInfo.Name,
            .ImageIndex = 1,
            .Tag = fileInfo.FullName
            }

        lvsi = New ListViewItem.ListViewSubItem With {
            .Text = fileInfo.Length.ToString()
            }

        lvi.SubItems.Add(lvsi)

        lvsi = New ListViewItem.ListViewSubItem With {
            .Text = fileInfo.LastAccessTime.ToString()
            }

        lvi.SubItems.Add(lvsi)

        ListView1.Items.Add(lvi)
    Next

    'after populating the list this will size columns to the width of column data
    ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
    Label1.Text = "C:\Users\yourName\Documents" + Environment.NewLine + " (Double click to open file !)"

    AddHandler ListView1.ItemActivate, AddressOf ListView1_ItemActivate
End Sub

Private Sub ListView1_ItemActivate(sender As Object, e As System.EventArgs)
    Dim filename As String = ListView1.SelectedItems(0).Tag.ToString()

    Try
        Process.Start(filename)
    Catch
        Return
    End Try
End Sub
E.Georgiev
  • 72
  • 2