Alright, so I can't figure out why I can't write to a file. It says it's being used by another process. Here's the error (IOException was unhandled):
The process cannot access the file 'C:\Temp\TempFile.cfg' because it is being used by another process.
Here's the current code I'm using to write to the file:
Dim myConfig
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Configuration Files (*.cfg)|*.cfg"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myConfig = saveFileDialog1.OpenFile()
If (myConfig IsNot Nothing) Then
System.IO.File.WriteAllText(saveFileDialog1.FileName, TextBox1_Output_Module.Text & vbCrLf & TextBox2_Output_Module.Text & vbCrLf & TextBox3_Output_Module.Text)
myConfig.Close()
End If
End If
I'm not sure what I am missing as I thought I tested this yesterday and it worked.
I suppose that the process that keep the file open is your own process.
When you call saveDialog1.OpenFile(), you are opening the file and a stream is returned.
Then you call WriteAllText() that tries to open again the same file resulting in the exception above.
You could solve simply removing the call to OpenFile()
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
File.WriteAllText(saveFileDialog1.FileName, TextBox1_Output_Module.Text & vbCrLf & TextBox2_Output_Module.Text & vbCrLf & TextBox3_Output_Module.Text)
End If
Just keep in mind that WriteAllText() creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
Well here's what I ended up doing, seems to be working just fine as is. I took out the if condition and left everything else as is. I can always code for the cancel later on.
Dim myConfig
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Configuration Files (*.cfg)|*.cfg"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
System.IO.File.WriteAllText(saveFileDialog1.FileName, TextBox1_Output_Module.Text & vbCrLf & TextBox2_Output_Module.Text & vbCrLf & TextBox3_Output_Module.Text)
This codes for the ok/cancel button.
If saveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
System.IO.File.WriteAllText(saveFileDialog1.FileName, TextBox1_Output_Module.Text & vbCrLf & TextBox2_Output_Module.Text & vbCrLf & TextBox3_Output_Module.Text)
End If
Related
I've been working on a script, a windows console application, that reads a .CSV for a file-path and other various information and then using System.IO.File.Copy to copy the file to a new directory and give it a new name. The file's im working with are .WAV files. Essentially I take a peek at the .CSV provided, then grab the filepath from there, then rename the file using different columns from the .CSV with dot-notation. I.E. Acc.Date.Name.Type.wav.
However, I'm experiencing "NotSupportedException" error on the line that copies and create the new file. The sub message is "The given paths format is not supported." Now, I've fairly new to VB code, I' assuming right now that .WAV format is not supported.
I'm not sure what all to add, if anything is needed let me know.
Here is the script so far:
Module Module1
Sub Main()
Dim fileLine As String
Dim aryTextFile() As String
Dim objReader As New System.IO.StreamReader("C:\Temp\EDCallFilePaths.csv")
Do While objReader.Peek() <> -1
fileLine = fileLine & objReader.ReadLine() & vbNewLine
aryTextFile = fileLine.Split(",")
If Not aryTextFile(7) = "null" Then
System.IO.File.Copy(aryTextFile(7), "C:\Temp\" & aryTextFile(0) & "." & aryTextFile(2) & "." & aryTextFile(3) & "." & aryTextFile(4) & "." & aryTextFile(5) & "." & aryTextFile(6) & ".wav")
fileLine = ""
End If
Loop
End Sub
End Module
I should note, column 7 is the filepath to the recording
I have used dotnetbar devcomponents advanced treeview to create multiple directory trees for one of my projects. Functionality wise, everything is working fine.
I have now added images to the directory file nodes (e.g. pdf image if its a pdf file) and published the application. The application runs without any errors first time on any machine, but once I close this File Management form (I have a control panel form with buttons that is the initial startup form. The buttons take me to other forms. On button click, it hides the control panel and displays the corresponding form through showdialog - File Management form is one of those buttons) and reopen it again - I get the following error:
parameter_is_not_valid
It then fails to load the nodes and after a couple of tries, Microsoft .Net Framework window appears and ends the application.
I get the images from my resource file. Please see the code for LoadAllSubDirectoriesFiles where the error occurs:
Private Sub LoadAllSubDirectoriesFiles(ByVal uParent As DevComponents.AdvTree.Node)
' Initialise Error Checking
Dim uStackframe As New Diagnostics.StackFrame
Dim ufile As IO.FileInfo = Nothing
Try
If uParent.Name.Length <> 248 Then
Dim files As IO.FileInfo() = uParent.Tag.GetFiles()
For Each file As IO.FileInfo In files
If (Not file.Attributes.ToString.Contains("Hidden")) Then
Dim uNode As DevComponents.AdvTree.Node = New DevComponents.AdvTree.Node()
uNode.Tag = file
uNode.Name = file.FullName.ToLower
uNode.Text = file.Name
If file.Extension = ".msg" Then
uNode.Image = My.Resources.Resources.Mail3
ElseIf file.Extension = ".txt" Then
uNode.Image = My.Resources.Resources.Document
ElseIf file.Extension = ".pdf" Then
uNode.Image = My.Resources.Resources.pdf
ElseIf file.Extension = ".doc" OrElse file.Extension = ".docx" Then
uNode.Image = My.Resources.Resources.doc
ElseIf file.Extension = ".xlsx" Then
uNode.Image = My.Resources.Resources.excel
ElseIf file.Extension = ".pub" Then
uNode.Image = My.Resources.Resources.publisher
ElseIf file.Extension = ".pptx" Then
uNode.Image = My.Resources.Resources.powerpoint
ElseIf file.Extension = ".bmp" OrElse file.Extension = ".png" OrElse file.Extension = ".jpg" OrElse file.Extension = ".gif" OrElse file.Extension = ".tif" Then
uNode.Image = My.Resources.Resources.bitmap_image
ElseIf file.Extension = ".zip" OrElse file.Extension = ".rar" Then
uNode.Image = My.Resources.Resources.zip
Else
uNode.Image = My.Resources.Resources.unknown
End If
uNode.DragDropEnabled = True
uParent.Nodes.Add(uNode)
End If
Next
End If
Catch ex As Exception
' Catch Error
If Err.Number <> 0 Then
WriteAuditLogRecord(uStackframe.GetMethod.DeclaringType.FullName, uStackframe.GetMethod.Name.ToString, "Error", ex.Message & vbCrLf & vbCrLf & ex.StackTrace, 0)
MsgBox("System Error Ref: " & sAuditID & vbCrLf & uStackframe.GetMethod.DeclaringType.FullName & " / " & uStackframe.GetMethod.Name.ToString & vbCrLf & ex.Message & vbCrLf & vbCrLf & ex.StackTrace & Chr(13) & sErrDescription & vbCrLf & vbCrLf & "Press Control + C to copy this error report", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Business Management System - Unexepected Error Ref: " & sAuditID)
End If
Finally
' CleanUp
End Try
End Sub
I have spent 2 days now trying to figure out the cause and fix for this problem. There were posts that talked about the image being disposed and not being able to retrieve the image reference [ http://blog.lavablast.com/post/2007/11/29/The-Mysterious-Parameter-Is-Not-Valid-Exception.aspx ] , cloning the image before disposing etc.
I have given disposing and cloning a go, but the error still stands. Been trying couple of other things, but still unsuccessful.
Any suggestions to what is wrong?
EDIT 1
Before closing the form, I clear all the treenodes and then use Me.Close()
Private Sub tsbClose_Click(sender As Object, e As EventArgs) Handles tsbClose.Click
atRootFolder.Nodes.Clear()
atAllDirectories.Nodes.Clear()
atScannedFiles.Nodes.Clear()
atFiles.Nodes.Clear()
atInbox.Nodes.Clear()
atSent.Nodes.Clear()
Me.Close()
End Sub
EDIT 2
My treeviews have hundreds of nodes, child nodes etc. Please see the image of my File Management form ( this is the first time it was loaded, no errors) I had to hide the text due to client confidentiality, but I hope it makes sense. Each image is a node.
imgur.com/QQ2FzFV
I had tried to use GC.Collect to see if it works, and surprising it did. Sadly it worked on one machine and didn't in another. Therefore, instead of calling images directly from my resources, I have stored all required images in an image list which I have attached to my treeviews. It's working like a charm.
I'm making a skype tool, and I'm creating the config file automatically, or at least that's what I think I am doing. The problem is just that for some reason the FileNotFoundException is fired because of some of my code is refering to the file which doesn't exist yet. So is visual basic checking for exceptions before firing code, or am I doing something wrong?
Here's my file creation code:
If My.Computer.FileSystem.DirectoryExists("C:\BaconSkypeTool") Then
Else
My.Computer.FileSystem.CreateDirectory("C:\BaconSkypeTool")
End If
If My.Computer.FileSystem.FileExists(Path) Then
Else
Dim fs As FileStream = File.Create(Path)
Dim line1 As Byte() = New UTF8Encoding(True).GetBytes("This is the configuration file for BaconSkypeTool" & vbCrLf & "Please do not change anything in here if you don't know what you're doing." & vbCrLf & vbCrLf & "Values below" & vbCrLf & "ChangeStatusInCall = True" & vbCrLf & "Status = Online" & vbCrLf & "Enable .cancel command = True")
fs.Write(line1, 0, line1.Length)
fs.Close()
End If
And here's the code that fires the exception:
skype.CurrentUserStatus = SKYPE4COMLib.TOnlineStatus.olsOnline
Dim text = My.Computer.FileSystem.ReadAllText("C:\BaconSkypeTool\config.cfg")
Dim textAfterStatus As String = Nothing
Dim indexOfStatus = text.IndexOf("Status = ")
Dim text1 As String = Nothing
If indexOfStatus >= 0 Then
textAfterStatus = text.Substring(indexOfStatus + "Status = ".Length)
text1 = textAfterStatus.Split("Blacklist").First().Trim()
End If
The file creation is at the top of my file and therefore should be the first thing to be fired, but maybe that's just something I think.
I was trying to save multiple image to a local folder in one go in vb. Right now, i am able to save one image at a time to a specified folder. In my code, i have set up a file name for the image to use when uploaded. What I needed is to save the image with it's original file name and file type. My program should also allow user to save multiple images in one go.
I am Using VB 2013 Ultimate
this is the code for searching.
Try
a.Filter = "Image files | *.*"
If a.ShowDialog() = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(a.FileName)
PictureBox1.BackgroundImageLayout = ImageLayout.Stretch
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
and this is my code for saving
If (Not System.IO.Directory.Exists("d:/Site Images/" & Label33.Text & "/")) Then
System.IO.Directory.CreateDirectory("d:/Site Images/" & Label33.Text & "/")
End If
'Dim address = ("d:/Site Images/" & a.FileName & ".jpg")
PictureBox1.Image.Save("d:/Site Images/" & Label33.Text & "/" & "a.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
thanks for the help.
A sample snippet
Dim a As New OpenFileDialog
a.Filter = "Jpeg Files|*.jpg"
a.ShowDialog()
For i As Integer = 0 To a.FileNames.Count - 1
Try
Dim img As Image = Image.FromFile(a.FileNames(i))
img.Save("Your Saving Path")
Catch ex As Exception
End Try
Next
I'm currently using the Directory.Move method to copy files from one location to another. What i would like to do is only move files with certain extensions (.dbf, .ini & .txt). If the original folder doesn't contain any of these files then i just want to create an empty directory
Current code I'm using is...
Dim n As Integer
If lb1.SelectedItems.Count = 0 Then Exit Sub
For n = 0 To UBound(AllDetails)
If AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps = lb1.SelectedItem Then
If Not My.Computer.FileSystem.DirectoryExists(aMailbox & "\" & AllDetails(n).uFile) Then
Directory.Move(zMailbox & AllDetails(n).uFile, aMailbox & "\" & AllDetails(n).uFile)
lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
Else
lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
Exit Sub
End If
End If
Next
All the variables are declared and this works but moves the entire folder contents
One way to approach this is to use each extension as a search pattern for File.GetFiles, then use Directory.Move on each file returned. Something like this might help:
For Each OldFile As String In (From s In {".dbf", ".ini", ".txt"}
From f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, s)
Select f)
Directory.Move(OldFile, aMailbox & "\" & AllDetails(n).uFile & "\" & Path.GetFileName(OldFile))
Next
if what you want is certain file extensions only? well Open File Dialog can filter that for you
Let's say you call this operation with a button click:
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Open File Dialog"
fd.InitialDirectory = "the initial directory you want to look at first"
'this filters the available files to be opened!
fd.Filter = "dbf files|*.dbf*|ini files|*.ini*|Text files|*.txt*"
fd.FilterIndex = 2 'set's the default files to open first as .ini
fd.RestoreDirectory = True
If fd.ShowDialog() = Windows.Forms.DialogResult.OK Then
'Copy the file to the location using the copyer subroutin
resulta.Text = fd.FileName.ToString
Copyer(fd.FileName.Tostring, "the location where you want to copy")
End If
End Sub
Now for the copying of the file, have a look at this subroutine. This subroutine checks first if the file exists. If it does, it deletes it, then copies the new file.
Public Sub Copyer(ByVal theFile As String, ByVal Lokasyon As String)
Try
Dim resultpath As String = Lokasyon
If System.IO.File.Exists(resultpath) = True Then
System.IO.File.Delete(resultpath)
'this deletes the file so you can overwrite it.
End If
My.Computer.FileSystem.CopyFile(theFile, resultpath)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Please let me know if this has helped you.