Upload and replace the same image file if it already exist - vb.net

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

Related

Resizing multiple images and saving them to a separate folder

I need to resize and compress 200 images that I have stored in a folder.
I am getting these images in a list using this code that I got from another question:
Dim dir = New IO.DirectoryInfo("C:\\Users\\Charbel\\Desktop\\Images")
Dim images = dir.GetFiles("*.jpg", IO.SearchOption.AllDirectories).ToList
Dim pictures As New List(Of PictureBox)
For Each img In images
Dim picture As New PictureBox
picture.Image = Image.FromFile(img.FullName)
pictures.Add(picture)
Next
Now, I need to compress and reduce each image to (500x374) and then save them in another folder on my PC.
Well, let me first point out a couple of points about your code:
PictureBox doesn't serve any purpose here. You shouldn't create a PictureBox to use the Image.
Always remember to dispose the Image object (e.g., by wrapping it in a Using block) so you don't run into memory issues.
Unlike C#, VB.NET doesn't require escaping the \ character, therefore, you can write your path like this "C:\Users...".
Now, for resizing the image, you can simply create an instance of the Bitmap class with the constructor that takes an image and a size argument: Bitmap(Image, Size) or Bitmap(Image, Int32, Int32).
Here:
Dim sourcePath As String = "C:\Users\Charbel\Desktop\Images"
Dim outputPath As String = "C:\Users\Charbel\Desktop\Images\Resized"
IO.Directory.CreateDirectory(outputPath)
Dim dir = New IO.DirectoryInfo(sourcePath)
Dim files As IO.FileInfo() = dir.GetFiles("*.jpg", IO.SearchOption.AllDirectories)
For Each fInfo In files
Using img As Bitmap = Image.FromFile(fInfo.FullName)
Using resizedImg As New Bitmap(img, 500, 374)
resizedImg.Save(IO.Path.Combine(outputPath, fInfo.Name),
Imaging.ImageFormat.Jpeg)
End Using
End Using
Next

How to Access a txt file in a Folder created inside a VB project

I'm creating a VB project for Quiz App (in VS 2013). So I have some preset questions which are inside the project (I have created a folder inside my project and added a text file).
My question is how can I read and write contents to that file? Or if not is there any way to copy that txt file to Documents/MyAppname when installing the app so that I can edit it from that location?
In the example below I am focusing on accessing files one folder under the executable folder, not in another folder else wheres. Files are read if they exists and then depending on the first character on each line upper or lower case the line then save data back to the same file. Of course there are many ways to work with files, this is but one.
The following, created in the project folder in Solution Explorer a folder named Files, add to text files, textfile1.txt and textfile2.txt. Place several non empty lines in each with each line starting with a character. Each textfile, set in properties under solution explorer Copy to Output Directory to "Copy if newer".
Hopefully this is in tune with what you want. It may or may not work as expected via ClickOnce as I don't use ClickOnce to validate this.
In a form, one button with the following code.
Public Class Form1
Private TextFilePath As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Files")
Private TextFiles As New List(Of String) From
{
"TextFile1.txt",
"TextFile2.txt",
"TextFile3.txt"
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = ""
' loop thru each file
For Each fileBaseName As String In TextFiles
FileName = IO.Path.Combine(TextFilePath, fileBaseName)
' only access file if it exist currently
If IO.File.Exists(FileName) Then
' read file into string array
Dim contents As String() = IO.File.ReadAllLines(FileName)
' upper or lower case line based on first char.
' this means you can flip flop on each click on the button
For x As Integer = 0 To contents.Count - 1
If Char.IsUpper(CChar(contents(x))) Then
contents(x) = contents(x).ToLower
Else
contents(x) = contents(x).ToUpper
End If
Next
' save changes, being pesstimistic so we use a try-catch
Try
IO.File.WriteAllLines(FileName, contents)
Catch ex As Exception
Console.WriteLine("Attempted to save {0} failed. Error: {1}",
FileName,
ex.Message)
End Try
Else
Console.WriteLine("Does not exists {0}", FileName)
End If
Next
End Sub
End Class
This may help you
Dim objStreamReader As StreamReader
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
'Close the file.
objStreamReader.Close()
Console.ReadLine()
You can also check this link.

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 save the contents (Not Texts Nor Images) of a form with a custom extension and open the saved custom file

I need some help for the project I am working on for my internship.
In the VB project, I have a windows form (Form1.vb) with a custom user control called WaveForm1 (which acts like the graph of an oscilloscope). I can run the VB program and assign values to the channels to get the wave forms in the WaveForm1 user control when the project is running.
Then, I need to save the WaveForm1 together with the Channels plotted in the graph under a custom file extension (.gph, .wfm ,..) using a SaveFileDialog.
The saved file should be able to open in the vb project when it is opened with a button (btnOpen) by using a OpenFileDialog.
How the file is opened in the project doesn't matter as long as the saved graph can be viewed. ( Example, the saved file can be viewed in another WaveForm2 control in Form1.vb or it can be viewed in a separate window form.) It would also be fine if the whole formed can be saved and opened again from the project with the btnOpen button control.
I have searched about custom file creations & saving files and all I could find were how to save text files, excel files or images using a StreamWriter/Reader, binaryReader/Writer, and so on.
I would really appreciate any help regarding saving anything other than text files or drawings.
Please feel free to confirm with me if you are not clear about my questions.
You should try to create a class with some properties then you can save that class using BinarryFormatter. You can give your custom extension to that class and save it through SaveFileDialog and open it by OpenFileDialog.
Class
<Serializable()>
Public Class myGraph
Private _value1 As String
Public Property Value1 As String
Get
Return _value1
End Get
Set(value As String)
_value1 = value
End Set
End Property
Private _value2 As String
Public Property Value2 As String
Get
Return _value2
End Get
Set(value As String)
_value2 = value
End Set
End Property
Private _value3 As String
Public Property Value3 As String
Get
Return _value3
End Get
Set(value As String)
_value3 = value
End Set
End Property
End Class
Method to to Save and Load File
''To Save file
Public Sub SaveFile(GRAPH_1 As myGraph)
''To Save File
Dim dlgSave As New SaveFileDialog
dlgSave.Filter = "My File|*.grp"
dlgSave.DefaultExt = ".gpr"
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim formatter As New BinaryFormatter
Using stream As New MemoryStream
formatter.Serialize(stream, GRAPH_1)
Using sw As New FileStream(dlgSave.FileName, FileMode.Create)
Dim data() As Byte = stream.ToArray()
sw.Write(data, 0, data.Length)
End Using
End Using
End If
End Sub
''To Load fie
Public Function LoadFile() As myGraph
Dim GRAPH_2 As myGraph = Nothing
Dim dlgOpen As New OpenFileDialog
dlgOpen.Filter = "My File|*.grp"
If dlgOpen.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim formatter As New BinaryFormatter
Using stream As New FileStream(dlgOpen.FileName, FileMode.Open)
GRAPH_2 = TryCast(formatter.Deserialize(stream), myGraph)
End Using
End If
Return GRAPH_2
End Function
How to Use File
''To Save File
Dim GRAPH_1 As New myGraph
With GRAPH_1
.Value1 = "ABC"
.Value2 = "XYZ"
.Value3 = "PQR"
End With
SaveFile(GRAPH_1)
''ToLoad File
Dim GRAPH_2 As myGraph = LoadFile()
If GRAPH_2 IsNot Nothing Then
''Place your code here
''And assign values to your graph from that (myGraph)class.
End If

how to load a file from folder to memory stream buffer

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.