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.
Related
I create a plugin for MS Word by VSTO VB.NET
I Wrote the function to copy two files to the AppData folder from Resources.
The code works fine and copy files, but create the Additional files (file size is 0) in MyDocumnet and my doc file location.
How can I fix it?
Public Function openFile(fName As String) As String
Dim path, fileName As String
Dim bytes, p
' Dim FileLocked As Boolean
p = Environment.GetEnvironmentVariable("APPDATA") & "\"
Select Case fName
Case "q"
bytes = My.Resources.qText
fileName = "qText.docx"
path = p & fileName
Case "t"
bytes = My.Resources.tText
fileName = "tText.docx"
path = p & fileName
End Select
Dim Locked As Boolean = False
Try
Dim fs As FileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)
fs.Close()
Catch
Locked = True
End Try
Try
If Locked Then
Return fileName
Else
File.WriteAllBytes(path, bytes)
If fileName = "QText.docx" Then
SourceApp.Documents.Open(FileName:=path, ReadOnly:=True, Visible:=False)
Else
SourceApp.Documents.Open(FileName:=path, Visible:=False)
SourceApp.Documents("tText.docx").Content.Delete()
End If
SourceApp.ScreenUpdating = False
SourceApp.DisplayStatusBar = False
Call ComMode()
Return fileName
End If
Catch ex As Exception
End Try
End Function
When you check whether a particular file exists/locked on the disk a relative path is used. Only the filename is passed which means the relative path:
Dim fs As FileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)
fs.Close()
But when you write the content the absolute path is specified in the code:
File.WriteAllBytes(path, bytes)
The path can point to another place. I'd suggest using the Directory.GetCurrentDirectory method which gets the current working directory of the application. If required you may set the current directory using the Environment.CurrentDirectory property sets the fully qualified path of the current working directory.
Shouldn't this:
Dim fs As FileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)
actually be this:
Dim fs As FileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)
As it stands, you're specifying only a file name rather than a file path, so the folder path has to be assumed to be some default, which is presumably where you're seeing those files created.
This is an example of why descriptive variable names are important. Personally, I would have used folderPath, fileName and filePath rather than p, fileName and path. It's far more obvious what each one is then.
What's the point of creating a file anyway? Why not check whether one exists first and then only try to open it if it does? You appear to be checking whether the file is locked but it obviously can't be locked if it doesn't exist.
Dim streamf As System.IO.Stream
Dim stringf As String
stringf = OpenFileDialog1.FileName.ToString()
streamf = OpenFileDialog1.OpenFile()
I have a file ScreenShot.png attached on the application installation path which means if user run the .exe file from Desktop it will store ScreenShot.png on his desktop and so on.
Now i need to get the full path to that ScreenShot.png file to be sent in the FAX
Dim srcBt As Byte()
Dim encodedBase64 As String
Dim filereader As New IO.FileStream(stringf, IO.FileMode.Open)
ReDim srcBt(filereader.Length)
filereader.Read(srcBt, 0, filereader.Length)
filereader.Close()
encodedBase64 = System.Convert.ToBase64String(srcBt)
So the problem part is how can i put that location of the file to the Stringf ? Because example i have force user to locate the file using OpenFileDialog and i have predefined file
This should convert any (relative) path to an absolut path:
Dim stringf_info As New System.IO.FileInfo(stringf)
stringf = stringf_info.FullName
I have a picturebox named PB_Company_Logo and I have a button named btn_Save and within this button I have this function which saves the image in PB_Company_Logo to current_directory/images
Public Sub save_PB(PB_Name As PictureBox)
Dim filename As String = "company_logo.png"
Dim path As String = Directory.GetCurrentDirectory() & "\images"
Dim filename_path As String = System.IO.Path.Combine(path, filename)
If (Not System.IO.Directory.Exists(path)) Then
System.IO.Directory.CreateDirectory(path)
PB_Name.Image.Save(filename_path)
Else
PB_Name.Image.Save(filename_path)
End If
End Sub
The problem is, there are cases where the user will upload a new company_logo.png. I want the system to treat the uploading of new image as replacing the former company_logo.png.
I think the error in this line of code means that the file is currently in used (locked) and therefore cannot be replaced.
Else
PB_Name.Image.Save(filename_path)
End If
When you load a pictureBox control with an image file the ide (vs) puts a lock on the file. This happens when you set the image property of the pictureBox control to a file at design time.
You can use the FileStream object.
Example:
Dim fs As System.IO.FileStream
' Specify a valid picture file path on your computer.
fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
After you have done the workaround you can then use the System.IO.File.Exists(img) namespace to check wether or not a picture exists.
Example: This checks if the image passed through already exists and if it does then it will replace it.
Dim imageStr As String = "~/images/name.jpg"
If System.IO.File.Exists(imageStr) Then
Image1.ImageUrl = "~/images/name.jpg"
End If
I have a .zip folder in the .exe resources and I have to move it out and then extract it to a folder. Currently I am moving the .zip out with System.IO.File.WriteAllByte and unziping it. Is there anyway to unzip straight from the resources to a folder?
Me.Cursor = Cursors.WaitCursor
'Makes the program look like it's loading.
Dim FileName As FileInfo
Dim Dir_ExtractPath As String = Me.tb_Location.Text
'This is where the FTB folders are located on the drive.
If Not System.IO.Directory.Exists("C:\Temp") Then
System.IO.Directory.CreateDirectory("C:\Temp")
End If
'Make sure there is a temp folder.
Dim Dir_Temp As String = "C:\Temp\Unleashed.zip"
'This is where the .zip file is moved to.
Dim Dir_FTBTemp As String = Dir_ExtractPath & "\updatetemp"
'This is where the .zip is extracted to.
System.IO.File.WriteAllBytes(Dir_Temp, My.Resources.Unleashed)
'This moves the .zip file from the resorces to the Temp file.
Dim UnleashedZip As ZipEntry
Using Zip As ZipFile = ZipFile.Read(Dir_Temp)
For Each UnleashedZip In Zip
UnleashedZip.Extract(Dir_FTBTemp, ExtractExistingFileAction.DoNotOverwrite)
Next
End Using
'Extracts the .zip to the temp folder.
So if you're using the Ionic library already, you could pull out your zip file resource as a stream, and plug that stream into Ionic to decompress it. Given a resource of My.Resources.Unleashed, you have two options for getting your zip file into a stream. You can load up a new MemoryStream from the bytes of the resource:
Using zipFileStream As MemoryStream = New MemoryStream(My.Resources.Unleashed)
...
End Using
Or you can use the string representation of the name of the resource to pull a stream directly from the assembly:
Dim a As Assembly = Assembly.GetExecutingAssembly()
Using zipFileStream As Stream = a.GetManifestResourceStream("My.Resources.Unleashed")
...
End Using
Assuming you want to extract all the files to the current working directory once you have your stream then you'd do something like this:
Using zip As ZipFile = ZipFile.Read(zipFileStream)
ForEach entry As ZipEntry In zip
entry.Extract();
Next
End Using
Taking pieces from here and there, this works with 3.5 Framework on Windows 7:
Dim shObj As Object = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"))
Dim tmpZip As String = My.Application.Info.DirectoryPath & "\tmpzip.zip"
Using zip As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("myProject.myfile.zip")
Dim by(zip.Length) As Byte
zip.Read(by, 0, zip.Length)
My.Computer.FileSystem.WriteAllBytes(tmpZip, by, False)
End Using
'Declare the output folder
Dim output As Object = shObj.NameSpace(("C:\destination"))
'Declare the input zip file saved above
Dim input As Object = shObj.NameSpace((tmpZip)) 'I don't know why it needs to have double parentheses, but it fails without them
output.CopyHere((input.Items), 4)
IO.File.Delete(tmpZip)
shObj = Nothing
Sources: answers here and https://www.codeproject.com/Tips/257193/Easily-Zip-Unzip-Files-using-Windows-Shell
Since we are using the shell to copy the files, it will ask the user to overwrite them if already exist.
I am working on vb.net win form. My task is display the file names from a folder onto gridview control. when user clicks process button in my UI, all the file names present in gridview, the corresponding file has to be loaded onto memory stream buffer one after another and append the titles to the content of the file and save it in hard drive with _ed as a suffix to the file name.
I am very basic programmer. I have done the following attempt and succeeded in displaying filenames onto gridview. But no idea of later part. Any suggestions please?
'Displaying files from a folder onto a gridview
Dim inqueuePath As String = "C:\Users\Desktop\INQUEUE"
Dim fileInfo() As String
Dim rowint As Integer = 0
Dim name As String
Dim directoryInfo As New System.IO.DirectoryInfo(inqueuePath)
fileInfo = System.IO.Directory.GetFiles(inqueuePath)
With Gridview1
.Columns.Add("Column 0", "FileName")
.AutoResizeColumns()
End With
For Each name In fileInfo
Gridview1.Rows.Add()
Dim filename As String = System.IO.Path.GetFileName(name)
Gridview1.Item(0, rowint).Value = filename
rowint = rowint + 1
Next
Thank you very much for spending your valuable time to read this post.
to read a file into a memorystream is quite easy, just have a look at the following example and you should be able to convert it to suite your needs:
Dim bData As Byte()
Dim br As BinaryReader = New BinaryReader(System.IO.File.OpenRead(Path))
bData = br.ReadBytes(br.BaseStream.Length)
Dim ms As MemoryStream = New MemoryStream(bData, 0, bData.Length)
ms.Write(bData, 0, bData.Length)
then just use the MemoryStream ms as you please. Just to clearify Path holds the full path and filename you want to read into your memorystream.