Unknown error wont open from computer. Basic - vb.net

Sub ShowFileContents(ByVal strFileName As String)
Dim fs As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Dim TextFile As New StreamReader(fs)
Me.txtFileContents.Text = Nothing
Dim strLineOfText As String
Do While TextFile.Peek > -1
strLineOfText = TextFile.ReadLine()
Me.txtFileContents.Text = Me.txtFileContents.Text & strLineOfText & vbCrLf
Loop
TextFile.Close()
fs.Close()
End Sub
Why cant I open a file when I run program all it says is "Save" or "Cancel"

Why cant I open a file when I run program all it says is "Save" or "Cancel" What Im trying to do is open a file from my documents and display it in the textbox below. I have the save file working but not the open file
It looks like you could benefit from using the OpenFileDialog control rather than a textbox to get the file path you want to open.
Here's an example:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim ofp As New OpenFileDialog
If ofp.ShowDialog = Windows.Forms.DialogResult.OK Then
ShowFileContents(ofp.FileName)
End If
End Sub
Sub ShowFileContents(ByVal strFileName As String)
Dim TextFile As New StreamReader(strFileName)
txtFileContents.Text = Nothing
Do While Not TextFile.EndOfStream
txtFileContents.AppendText(TextFile.ReadLine() & vbCrLf)
Loop
TextFile.Close()
End Sub

Related

File.create shows no errors but doesnt create file?

I'm trying to copy a file from an external drive by reading its contents, creating a new file elsewhere and writing the contents into it. My code shows no errors (using MSV) but when I try to 'download' the file, it completes the code but no file is created.
Can anyone help?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim FileReader As String
FileReader = My.Computer.FileSystem.ReadAllText(Label32.Text)
Dim fbd As FolderBrowserDialog = New FolderBrowserDialog
Dim DownloadLocation As String
If fbd.ShowDialog() <> DialogResult.Cancel Then
DownloadLocation = fbd.SelectedPath
File.Create(fbd.SelectedPath & "pandora speedsign log.txt").Dispose()
File.WriteAllText(fbd.SelectedPath & "pandora speedsign log.txt", FileReader)
MessageBox.Show("success!!")
End If
'File.Create("C:\Users\%UserProfile%\Downloads" & DownloadFileDate & ".txt")
'File.WriteAllText("C:\Users\%USERPROFILE%\Downloads" & DownloadFileDate & ".txt", FileReader)
End Sub
I've been looking for different ways of creating the file, different ways of writing the file but nothing seems to work.
We can significantly simplify the code like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fbd As New FolderBrowserDialog()
If fbd.ShowDialog() <> DialogResult.Ok Then Exit Sub
Dim outputPath As String = IO.Path.Combine(fbd.SelectedPath, "pandora speedsign log.txt")
IO.File.Copy(Label32.Text, outputPath)
End Sub

Opening a file from List View?

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
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

File is not shown in OpenFileDialog

I'm trying to do something like a text editor in VB 2012, so I have a MenuStrip with an "OpenFile" option. When it's clicked it fires an OpenFileDialog control and shows me just the files with the extension I want. The problem is that if I close the file with another option in the menu strip, when I want to open the same file I opened the first time using the same OpenFile option the OpenFileDialog is not showing me the file.
Do you know why is that?
Here is how I open the file:
Private Sub OpenFileToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenFileToolStripMenuItem.Click
'Open File
If OpenFile.ShowDialog() = Windows.Forms.DialogResult.OK Then
If Not (OpenFile.FileName = "") And OpenFile.CheckFileExists Then
NewFile = New StreamReader(OpenFile.FileName)
If NewFile IsNot Nothing Then
Me.TextBox_Main.Text = NewFile.ReadToEnd
Me.TabPage1.Text = OpenFile.FileName.Substring(OpenFile.FileName.LastIndexOf("\") + 1)
End If
End If
End If
End Sub
And here is how I close the file:
Private Sub CloseFileToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseFileToolStripMenuItem.Click
'Close Files
If NewFile IsNot Nothing Then
NewFile.Close()
NewFile = Nothing
End If
Me.TextBox_Main.Text = ""
Me.TabPage1.Text = "New Tab"
End Sub

Im cant get a doc from my documents to display

Imports System.IO
Public Class Form1
Private Sub MenuItem1_Click(sender As Object, e As EventArgs) Handles MenuItem1.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem2_Click(sender As Object, e As EventArgs) Handles MenuItem2.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem3_Click(sender As Object, e As EventArgs) Handles MenuItem3.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim TextFile As New StreamWriter(fs)
TextFile.Write(Me.txtFileContent.Text)
TextFile.Close()
fs.Close()
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Dim TextFile As New StreamWriter(fs)
TextFile.Close()
fs.Close()
End Sub
End Class
What im trying to do is display a "open" document dialog box so the text inside the box can be displayed into the text box. I did the same with the "save" document dialog box and it worked fine just confused on the Open part. Thanks a million everyone.
There are two different kind of dialog box for selecting files.
One for save operations and one for opening files.
Your code seems to use the same one and from the name I think it is a SaveFileDialog.
To open a file you need a OpenFileDialog and use a StreamReader not a StreamWriter
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
' Create an OpenFileDialog here, for more precise property settings see the link above'
Dim openDlg = New OpenFileDialog()
' If user presses OK'
if openDlg.ShowDialog() = DialogResult.OK Then
' Still the filename selected could be empty, need to check'
Dim strFileName As String = openDlg.FileName
if strFileName.Trim().Length > 0 then
' Open the file using a reader, not a writer'
Using fs = New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Using TextFile = New StreamReader(fs)
' Read everything (caution this should be used only for small files)'
Dim fileContent = TextFile.ReadToEnd
' Pass everything into a TextBox control for display'
Me.txtFileContent.Text = fileContent
End Using
End Using
End If
End If
End Sub

Trying to open a docx file from a bytestream - file corruption error

we consistently get a file corrupted error message when opening a docx file from a saved bytestream, evry other file type works just ok
Below is code from a sample form that replciate the issue
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Objective is to be able to copy a file to a bytestream then create a new document from that stream and then opne it.
'This replicates the behaviour of our primary application where it stores and retrieves the stream from a database
'With docx files we consistently experience some sort of corruption in the write of the original file
'When selecting .doc or other format files we do not encounter the same problem
'use selected file
Dim _o1 As String = TextBox1.Text
'get its bytestream
Dim fs As New FileStream(_o1, FileMode.Open, FileAccess.Read)
Dim byteStream(Convert.ToInt32(fs.Length)) As Byte
fs.Read(byteStream, 0, Convert.ToInt32(fs.Length))
'create a new file and use the bytestream to create it and save to disk
Dim _o As String = "C:\" & Now.Ticks & getNewFileName()
Dim fs1 As New FileStream(_o, FileMode.OpenOrCreate, FileAccess.Write)
Using bw As New BinaryWriter(fs1)
bw.Write(byteStream)
bw.Flush()
End Using
'open the new document
System.Diagnostics.Process.Start(_o)
Application.DoEvents()
End Sub
Private Function getNewFileName() As String
Dim fi As New FileInfo(TextBox1.Text)
Return Now.Ticks.ToString & fi.Name
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.InitialDirectory = "c:\"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.Filter = "docx files |*.docx"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub
Forgive me, but that is some messed up code.
Dim _o As String = "C:\" & Now.Ticks & getNewFileName()
will become...
Dim _o As String = "C:\" & Now.Ticks & Now.Ticks.ToString & fi.Name
Example result "C:\" "634015010433498951" "634015010433498951" "FileName.txt" is probably not what you are expecting unless you intend to subtract the two tick counts to determine how long it took to populate FileInfo.
Your FileStream corruption could be a encoding issue, off by one file length issue, or even a long filename in a deep path could a problem. Instead of using FileStream, this code should work fine:
Dim sourceFile As String = TextBox1.text
Dim fi As New System.IO.FileInfo(sourceFile)
Dim destFile = "C:\" & Now.Ticks & fi.Name
fi.CopyTo(destFile)
'open the new document
System.Diagnostics.Process.Start(destFile)