In Form1 I have a Textbox1, in this textbox I have the location of a file "C:\folder\file.iso"
In the Form2 I want to get the file size of the file in Textbox1 so I tried this
Dim fileDetail As IO.FileInfo
fileDetail = My.Computer.FileSystem.GetFileInfo(Form1.Textbox1.Text)
Label1.Text = Size: fileDetail.Length
End Sub
I dont get an error, but the size of the file isn't showed in the label.
Edit: This doesn't seem to work
Private Sub Unscramble_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If System.IO.File.Exists(Form1.TextBox2.Text) Then
Dim fi As New System.IO.FileInfo(Form1.TextBox2.Text)
Label3.Text = "Size: " & fi.Length.ToString()
End If
End Sub
It still doesn't give me the size of the file nor it gives the "Size:"
Dim fileDetail = My.Computer.FileSystem.GetFileInfo(form1.Textbox1.Text)
Label1.Text = "Size : " & fileDetail.Length
' this is the first(main) form'
Public Class Form1
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
' create the form2 by PASSING it the file path in constructor'
Dim f2 As New Form2(TextBox1.Text)
f2.ShowDialog()
End Sub
End Class
' this is the second form'
Public Class Form2
Inherits Form
Private _filePath As String
Private Label1 As Label
Public Sub New(ByVal filePath As String)
_filePath = filePath
End Sub
' this is the _Load method of the second form'
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
If IO.File.Exists(_filePath) Then
Dim fi As New IO.FileInfo(_filePath)
Label1.Text = "Size :" & fi.Length.ToString()
End If
End Sub
End Class
Code works perfect but something in my project is blocking it.
Created a new project and it worked perfect.
'label3.Text is my all string with file size.
Label3.Text = "Size : " & My.Computer.FileSystem.GetFileInfo("C:\Download\my song.mp3").Length & " Bytes"
'Output: Size: 2344 Bytes
Label3.Text = "Size : " & System.Math.Round(My.Computer.FileSystem.GetFileInfo("C:\Download\my song.mp3").Length / 1024) & " KB"
'Output: Size: 2 KB
There is two choice, Which you want
Related
I want to download multiples files and the download links in list box, Is there any way to do that using WebClient, i saw people do that by download file by file by it look difficult way and i want to show current downloading speed ,current file size and progress of total process
I solved this proplem by that way:
Imports System.Net
Public Class Form1
Private WithEvents DonloadFile As WebClient
Dim stopwatch As Stopwatch = New Stopwatch
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.SelectedIndex = 0
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
stopwatch.Start()
DonloadFile = New WebClient
Try
DonloadFile.DownloadFileAsync(New Uri(ListBox1.SelectedItem.ToString), "C:\Users\" & Environment.UserName & "\Desktop\" & IO.Path.GetFileName(ListBox1.SelectedItem.ToString))
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DonloadFile_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles DonloadFile.DownloadProgressChanged
Dim y As Integer = (e.BytesReceived / 1024) / 1024
Label6.Text = "Download Speed: " & String.Format("{0} MB/s", (y / (stopwatch.Elapsed.TotalSeconds)).ToString("0.00"))
Label2.Text = "Current File Size: " & Math.Round(e.TotalBytesToReceive / (1024 * 1024), 1) & " MB"
Label3.Text = "Current File Persent: " & e.ProgressPercentage
Label1.Text = "Total Files: " & ListBox1.Items.Count.ToString()
If ListBox1.Items.Count.ToString > (ListBox1.SelectedIndex + 1) Then
If e.ProgressPercentage = 100 Then
ListBox1.SelectedIndex += 1
End If
Else
MessageBox.Show("Download completed successful", "Info")
End If
End Sub
Private Sub DonloadFile_DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs) Handles DonloadFile.DownloadDataCompleted
stopwatch.Reset()
End Sub
End Class
thanks for #Fawlty
Here is some code I wrote to demonstrate how you could do this. I created a FileDownloader class as this will allow you to get the source url and destination filename when the download completes. I have also added an event for progress. The problem with just using the WebClient class on its own is that you lose track of which file is being processed in the events.
Imports System.ComponentModel
Imports System.Net
' A class for downloading files, with progress and finished events
Public Class FileDownloader
' Private storage
Private FileURL As String = ""
Private SaveToPath As String = ""
' A class to return our result in
Public Class FileDownloaderFileDownloadedEventArgs
Public Property DownloadedURL As String
Public Property SaveToPath As String
Public Sub New(DownloadedURL As String, SaveToPath As String)
Me.DownloadedURL = DownloadedURL
Me.SaveToPath = SaveToPath
End Sub
End Class
' A class to show progress
Public Class FileDownloaderProgressEventArgs
Public Property DownloadURL As String
Public Property SaveToPath As String
Public Property TotalBytes As Long
Public Property ProgressBytes As Long
Public Property ProgressPercent As Integer
Public Property UserState As Object
Public Sub New(DownloadURL As String, SaveToPath As String, TotalBytes As Long, ProgressBytes As Long, ProgressPercent As Integer, UserState As Object)
Me.DownloadURL = DownloadURL
Me.SaveToPath = SaveToPath
Me.TotalBytes = TotalBytes
Me.ProgressBytes = ProgressBytes
Me.ProgressPercent = ProgressPercent
Me.UserState = UserState
End Sub
End Class
' The event to raise when the file is downloaded
Public Event FileDownloaded(sender As Object, e As FileDownloaderFileDownloadedEventArgs)
' The event to raise when there is progress
Public Event Progress(sender As Object, e As FileDownloaderProgressEventArgs)
' Pass in the URL and FilePath when creating the downloader object
Public Sub New(FileURL As String, SaveToPath As String)
Me.FileURL = FileURL
Me.SaveToPath = SaveToPath
End Sub
' Call Download() to do the work
Public Sub Download()
Using wc As New WebClient
AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
wc.DownloadFileAsync(New Uri(FileURL), SaveToPath)
End Using
End Sub
' Catch the download complete and raise our event
Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
RaiseEvent Progress(Me, New FileDownloaderProgressEventArgs(FileURL, SaveToPath, e.TotalBytesToReceive, e.BytesReceived, e.ProgressPercentage, e.UserState))
End Sub
Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
' Some code you want to run after each file has downloaded
RaiseEvent FileDownloaded(Me, New FileDownloaderFileDownloadedEventArgs(FileURL, SaveToPath))
End Sub
End Class
#Region "How to use the FileDownloader class"
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Loop the URLs in the ListBox
For Each item In ListBox1.Items
' Create a FileDownloader object to handler each one
Dim FD = New FileDownloader(item, "c:\temp\" & IO.Path.GetFileName(item))
' Attach the event handlers
AddHandler FD.FileDownloaded, AddressOf FileDownloaded
AddHandler FD.Progress, AddressOf Progress
' Start the download
FD.Download()
Next
End Sub
' Event handler for file download completed
Private Sub FileDownloaded(sender As Object, e As FileDownloader.FileDownloaderFileDownloadedEventArgs)
tb_Log.AppendText(e.DownloadedURL & " Downloaded To: " & e.SaveToPath & vbCrLf)
End Sub
' Event handler for progress
Private Sub Progress(sender As Object, e As FileDownloader.FileDownloaderProgressEventArgs)
tb_Log.AppendText(IO.Path.GetFileName(e.DownloadURL) & " " & e.ProgressPercent & "% downloaded" & vbCrLf)
End Sub
#End Region
What's wrong with this code?
I need to add textbox13.text (the value of it is in number) as the file name and how can I add an option which checks if the file already exists if so show an option saying replace or cancel when I press my save button.
So far here is the code :
Dim i As Integer = 0
Dim filepath As String = IO.Path.Combine("D:\Logs", Textbox13.Text + i.ToString() + ".txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(TextBox13.Text)
sw.WriteLine(TextBox1.Text)
sw.WriteLine(TextBox2.Text)
sw.WriteLine(TextBox3.Text)
sw.WriteLine(TextBox4.Text)
sw.WriteLine(TextBox5.Text)
sw.WriteLine(TextBox7.Text)
sw.WriteLine(TextBox9.Text)
sw.WriteLine(TextBox10.Text)
sw.WriteLine(TextBox11.Text)
sw.WriteLine(TextBox12.Text)
This is from Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Form2.WriteTextBoxTextToLabel(TextBox1.Text)
Form2.WriteTextBoxTextToTextbox(TextBox1.Text)
End Sub
This is from form2
Public Sub WriteTextBoxTextToLabel(ByVal Txt As String)
lblPD.Text = Txt
End Sub
Public Sub WriteTextBoxTextToTextbox(ByVal Txt As String)
TextBox13.Text = Txt
End Sub
Private Sub TextBox13_TextChanged(sender As Object, e As EventArgs) Handles TextBox13.TextChanged
TextBox13.Text = lblPD.Text
End Sub
You can add the following logic before creating the StreamWriter:
if system.io.file.exists(filepath) then
' The file exists
else
' The file does not exist
end if
I want to change USERname color inside RitchTextBox, I am using this code below to call the SUB but all the text now in red?
UPDATE
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & "$ ")
box.SelectionColor = Color.Black
box.AppendText(txtSend)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdSend.Click
' Shell("net send " & txtcomputer.Text & " " & txtmessage.Text)
Try
If txtPCIPadd.Text = "" Or txtUsername.Text = "" Or txtSend.Text = "" Then
MsgBox("wright a message!", "MsgBox")
Else
client = New TcpClient(txtPCIPadd.Text, 44444)
Dim writer As New StreamWriter(client.GetStream())
txttempmsg.Text = (txtSend.Text)
writer.Write(txtUsername.Text + " # " + txtSend.Text)
AddMessage(txtUsername.Text, txttempmsg.Text + vbCrLf)
'txtmsg.Text="You:" + txtmessage.Text)
writer.Flush()
txtSend.Text = ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
When you have a problem trying to get something to work in your program. It is easier to create a test example that you can then use to figure out what is happening without dealing with a lot of other variables in your larger program. In your case I created a VB Winforms app, added a RichTextBox, two TextBox's and a Button. By doing so I am able to show that the function is working.
Public Class Form1
Sub AddMessage(txtUsername As String, txtSend As String)
box.SelectionColor = Color.Red
box.AppendText(vbCrLf & txtUsername & " :") 'Note added colon
box.SelectionColor = Color.Black
box.AppendText(txtSend) 'Note changed variable name to parameter name
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddMessage(txtUsername.Text, txttempmsg.Text)
End Sub
End Class
Example:
I'm having some issues with WinForms ComboBox class. What I am trying to achieve is programmatically setting SelectedValue from the ComboBox.TextChanged handler once a match is found. This works fine on Windows 7, but in Windows XP SelectedValue will get set and SelectedValueChanged will be raised, but then once it reaches Validating SelectedValue returns Nothing. It seems the only way to change SelectedValue in XP is via selecting something from the dropdown.
Here's a toy Form with just a ComboBox and a multi-line TextBox.
XP: Typed into the ComboBox is 1Y, then tab is pressed. Output:
SelectedValueChanged: SelectedValue: 1X
Validating: SelectedValue: Nothing
Value is:
Validated: SelectedValue: Nothing
Win7: Typed into the ComboBox is 1Y, then tab is pressed. Output:
SelectedValueChanged: SelectedValue: 1X
Validating: SelectedValue: 1X
Value is: 1X
Validated: SelectedValue: 1X
Code:
Public Class ComboBoxXPForm
Private WithEvents mData As New DataHolder
Private mBindingSrc As BindingSource
Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
mBindingSrc = New BindingSource() With {.DataSource = mData}
Dim dt As New DataTable()
dt.Columns.Add("value", GetType(String))
dt.Columns.Add("displayValue", GetType(String))
dt.Rows.Add("", "")
For i = 1 To 10
dt.Rows.Add(i & "X", i & "Y")
Next
cboBox.DataSource = dt
cboBox.ValueMember = "value"
cboBox.DisplayMember = "displayValue"
cboBox.DataBindings.Add("SelectedValue", mBindingSrc, "StrVal", True)
End Sub
Private Sub cboBox_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboBox.SelectedValueChanged
txtDebug.Text &= vbNewLine & "SelectedValueChanged: SelectedValue: " & _
If(cboBox.SelectedValue Is Nothing, _
"Nothing", cboBox.SelectedValue.ToString())
End Sub
Private Sub DataHolder_DebugInfo(ByVal sender As Object, ByVal e As DebugEventArgs) Handles mData.DebugInfo
txtDebug.Text &= vbNewLine & e.DebugInfo
End Sub
Private Sub cboBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboBox.TextChanged
'For Each row In cboBox.Items
' If cboBox.Text = row("displayValue") AndAlso row("value") <> cboBox.SelectedValue Then
' 'cboBox.SelectedValue = row("value")
' cboBox.SelectedItem = row
' End If
'Next
For i = 0 To cboBox.Items.Count - 1
Dim item = cboBox.Items(i)
If cboBox.Text = item("displayValue") Then
cboBox.SelectedIndex = i
End If
Next
End Sub
Private Sub cboBox_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboBox.Validated
txtDebug.Text &= vbNewLine & "Validated: SelectedValue: " & _
If(cboBox.SelectedValue Is Nothing, _
"Nothing", cboBox.SelectedValue.ToString())
End Sub
Private Sub cboBox_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cboBox.Validating
txtDebug.Text &= vbNewLine & "Validating: SelectedValue: " & _
If(cboBox.SelectedValue Is Nothing, _
"Nothing", cboBox.SelectedValue.ToString())
End Sub
End Class
Public Class DebugEventArgs
Inherits EventArgs
Private mDebugInfo As String
Public Sub New(ByVal DebugString As String)
MyBase.New()
DebugInfo = DebugString
End Sub
Public Property DebugInfo() As String
Get
Return mDebugInfo
End Get
Set(ByVal value As String)
mDebugInfo = value
End Set
End Property
End Class
Public Class DataHolder
Public Event DebugInfo(ByVal sender As Object, ByVal e As DebugEventArgs)
Private mStrVal As String
Public Property StrVal() As String
Get
Return mStrVal
End Get
Set(ByVal value As String)
mStrVal = value
RaiseEvent DebugInfo(Me, New DebugEventArgs("Value is: " & value))
End Set
End Property
End Class
Try turning AutoCompleteMode to become SuggestAppend, and AutoCompleteSource to become ListItems. Then you can remove the entire TextChanged code block and it should also work properly on XP.
I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub