Visual Basic label - vb.net

If i have information (for example a name) in a label on a form in Visual Basic, how do I save this information in a .txt file?
Thanks

You can use the classes in the System.IO namespace. Look at File and its methods.
This example uses one overload of WriteAllText:
File.WriteAllText("Path To Text File.txt", myLabel.Text)
It will write the text value of the myLabel control to the specifies text file.

You use StreamWriter to do that. Here's an example:
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
If you want to know how to read from txt files, here's a example code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

You can use file system object for ealier versions of Visual basic.
' VBScript
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine(label.caption)
MyFile.Close
http://msdn.microsoft.com/en-us/library/z9ty6h50(VS.85).aspx
or
Sub Create_File()
Dim fso, txtfile
Set fso = CreateObject("Scripting.FileSystemObject")
Set txtfile = fso.CreateTextFile("c:\testfile.txt", True)
txtfile.Write (lable.caption) ' Write a line.
' Write a line with a newline character.
txtfile.WriteLine("Testing 1, 2, 3.")
' Write three newline characters to the file.
txtfile.WriteBlankLines(3)
txtfile.Close
End Sub
http://msdn.microsoft.com/en-us/library/aa263346(VS.60).aspx

Put it directly into the place you needed
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("filename.txt", True)
file.WriteLine("Your Text Here~")
file.Close()

Related

Writing/Reading from text files in VB.net

I am a student in computer science and for a project I need to be able to read from a text file in a way that each line is assigned to a space within an array. This should happen so that each line of text file is read in the order that it appears in the text file. I would also appreciate any methods of writing to a text file as well.
If this question is already explained, could you please direct me to the existing answer.
Things to note:
1) I am coding in a console application in VB.NET
2) I am relatively new at coding
You can do it like this:
Dim sFile As String = "D:\File.txt"
Dim aLines As String() = System.IO.File.ReadAllLines(sFile)
System.IO.File.WriteAllLines(sFile, aLines)
Here's a sample from the official documentation:
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText() As String = {"Hello", "And", "Welcome"}
File.WriteAllLines(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
Console.WriteLine(s)
Next
End Sub
End Class
Remarks
This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
Module Module1
Sub Main()
'Declare four variables
Dim oReader As New System.IO.StreamReader(".\archive01.txt") 'This file has to exist in the aplication current directory.
Dim oWriter As New System.IO.StreamWriter(".\archive02.txt") 'This file will be created by the software.
Dim oArray() As String = {}
Dim oString As String = Nothing
'For reading from .\archive01.txt and to load in oArray().
oString = oReader.ReadLine
While Not oString Is Nothing
If UBound(oArray) = -1 Then 'Ubound = Upper Bound, also exist LBound = Lower Bound.
ReDim oArray(UBound(oArray) + 1)
Else
ReDim Preserve oArray(UBound(oArray) + 1)
End If
oArray(UBound(oArray)) = New String(oString)
oString = oReader.ReadLine
End While
oReader.Close()
'For writing from oArray() to .\archive02.txt.
For i = 0 To oArray.Count - 1 Step 1
oWriter.WriteLine(oArray(i))
Next
oWriter.Close()
End Sub
End Module
Hi, try with this code. It works well. I hope that this helps to you to learn how to do this kind of things. Thank you very much. And happy codding!. :)

Write File with text from resources visual basic

I'm writing some program in VB, and I want to create txt file with text from file in resources. You didn't understood, did you? So, it goes like this.
Dim path As String = "c:\temp\MyTest.txt"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
fs.Write(info, 0, info.Length)
fs.Close()
is code for creating txt file with certain text. But, I need the following.
Dim fd As New FolderBrowserDialog
fd.ShowDialog()
is the only function that I have in program, and, when folder is selected, I need to create file in that folder, file's name should be config.cfg, but, text in file which is going to be created in selected folder should be text from mine txt file which is in Recources.
I've tried
Dim path As String = fd.SelectedPath
Dim fs As FileStream = File.Create(path)
' upisuje tekst u fajl
Dim info As Byte() = New UTF8Encoding(True).GetBytes(application.startuppath & "\..\..\Resources\config.cfg")
fs.Write(info, 0, info.Length)
fs.Close()
but the text I got in file is directory from where is my program debugged.
Any ideas to do this? :)
If you added a text file to your resources, then you can try something like this:
Using fbd As New FolderBrowserDialog
If fbd.ShowDialog(Me) = DialogResult.OK Then
File.WriteAllText(Path.Combine(fbd.SelectedPath, "config.cfg"), My.Resources.config)
End If
End Using
The file I added was called config, and it made a config.txt file in my resource library.

How to Zip an Excel File?

I have been trying to figure out how to zip an Excel .Xlsm file with no luck. The following code creates the zip file, but I can't figure out how to send the .xlsm file to it. Any help is appreciated!
Dim zipPath As String = RegScoringWorkbookName.Replace(".xlsm", ".zip") 'create zip file from .xlsm file
Try
If File.Exists(zipPath) Then
My.Computer.FileSystem.DeleteFile(zipPath, FileIO.UIOption.OnlyErrorDialogs,
FileIO.RecycleOption.DeletePermanently)
End If
Dim FilePath As String = RegScoringWorkbookName 'path of .xlsm file
Using FileStream = New FileStream(zipPath, FileMode.CreateNew)
Using archive = New ZipArchive(FileStream, ZipArchiveMode.Create, True)
Dim zipArchiveEntry = archive.CreateEntry(GetFileName(FilePath), CompressionLevel.Optimal)
Using zipStream = zipArchiveEntry.Open()
' zipStream.WriteAsync()
zipStream.Close()
End Using
End Using
End Using
Catch ex As Exception
End Try
I will just quote MSDN code here, since there is this exact example.
http://msdn.microsoft.com/de-de/library/vstudio/system.io.compression.ziparchive
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim zipPath As String = "c:\users\exampleuser\end.zip"
Dim extractPath As String = "c:\users\exampleuser\extract"
Dim newFile As String = "c:\users\exampleuser\NewFile.txt"
Using archive As ZipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Create) 'Changed this to create from MSDN
archive.CreateEntryFromFile(newFile, "NewEntry.txt", CompressionLevel.Fastest)
End Using
End Sub
End Module
It should be pretty self explanatory. There is no need to use a filestream at this point, as there is a premade method to zip an existing file, CreateEntryFromFile.

VB.net Read File Name from Dir to Run SQL Query

I have been asked to create a console application which polls an active Directory. (C.\Temp\Input)
When a file comes in with (filename).SUCCESS, filename is retrieve in order to run a SQL query. So
IF fileextension = SUCCESS
Runs SQL Query using filename to change a value in the SQL Table.
Moves Original file to c:\temp\Input\Processed
Any help or hints would be much appreciated.
UPDATED:
Hi, With a few looks at various sites iv come up with the below. Forgetting the SQL for now, im only after the Filename and the moving of files but im getting an IO Exception that the file is already in use:
Imports System.IO
Imports System.String
Module Module1
Dim fileName As String = "C:\temp\Input\NR12345.success"
Dim pathname As String = "C:\temp\Input\"
Dim result As String
Dim sourceDir As String = "C:\temp\Input\"
Dim processedDir As String = "C:\temp\Input\Processed\"
Dim fList As String() = Directory.GetFiles(sourceDir, "*.success")
Sub Main()
result = Path.GetFileName(fileName)
Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result)
result = Path.GetFileName(pathname)
Console.WriteLine("GetFileName('{0}') returns '{1}'", pathname, result)
Call MySub()
End Sub
Sub MySub()
'Move Files
For Each f As String In fList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length = 0)
Dim sourceFile = Path.Combine(sourceDir, fName)
Dim processedFileDir = Path.Combine(processedDir, fName)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(processedDir, fName), True)
'File.Copy(sourceFile, processedFileDir)
Next f
End Sub
End Module
I've used this before:
The FileWather Class
Really useful for polling directories for changes in structure and file details etc.
You can then use this to get an extension of a file and, if it meets your criteria, perform some actions.
These links come with examples so enjoy!!
Sub MySub()
'Move Files
For Each f As String In fList
Dim fInfo As FileInfo = New FileInfo(f)
Dim fName As String = fInfo.Name
Dim processedFileDir = Path.Combine(processedDir, fName)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(fInfo.FullName, processedFileDir, True)
Next f
End Sub

How to paste a file from Clipboard to specific path

How I can Paste from Clipboard a file to my path? I work in VB .NET. I got filename from clipboard but don't know how to extract file from cliboard and save it to my folder.
Dim data As IDataObject = Clipboard.GetDataObject()
If data.GetDataPresent(DataFormats.FileDrop) Then
Dim files As String() = data.GetData(DataFormats.FileDrop)
End If
Can anybody help me?
Thanks in advance!
You can use the Path class to both isolate the file name and create the path of the new file to use in a file copy operation:
Dim data As IDataObject = Clipboard.GetDataObject
If data.GetDataPresent(DataFormats.FileDrop) Then
For Each s As String In data.GetData(DataFormats.FileDrop)
Dim newFile As String = Path.Combine("c:\mynewpath", Path.GetFileName(s))
File.Copy(s, newFile)
Next
End If
Example needs error checking.
You can also get the full path to the file as follows:
Dim objeto As IDataObject = Clipboard.GetDataObject
For Each data As String In objeto.GetData(DataFormats.FileDrop)
...
Dim newFile As String = Path.GetFullPath(data.ToString)
...
Next