create file to another location in vb.net - vb.net

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.

Related

VB.net: overwrite everything in a text file

in my VB.net Application id like to overwrite and add new content of a text file
What Code do I need to use?
Thanks
Read (ie: load) everything in the TXT file into your program.
Dim sFullPathToFile As String = Application.StartupPath & "\Sample.txt"
Dim sAllText As String = ""
Using xStreamReader As StreamReader = New StreamReader(sFullPathToFile)
sAllText = xStreamReader.ReadToEnd
End Using
Dim arNames As String() = Split(sAllText, vbCrLf)
'Just for fun, display the found entries in a ListBox
For iNum As Integer = 0 To UBound(arNames)
If arNames(iNum) > "" Then lstPeople.Items.Add(arNames(iNum))
Next iNum
Because you wanted to overwrite everything in the file, we now use StreamWriter (not a StreamReader like before).
'Use the True to indicate it is to be appended to existing file
'Or use False to open the file in Overwrite mode
Dim xStreamWRITER As StreamWriter = New StreamWriter(sFullPathToFile, False)
'Use the carriage return character or else each entry is on the same line
xStreamWRITER.Write("I have overwritten everything!" & vbCrLf)
xStreamWRITER.Close()

Why does File.Open() not open the file?

I am implementing a Save File button in my VB.NET Windows Forms application.
I am attempting to encapsulate the normally expected behaviour of Save buttons in Windows applications. I.E: If a file was already selected then open the current file it, write to it and save it; else if there is no current file, or Save As was used, then show a SaveFileDialog, then open, write and save just the same.
I currently have coded the function below but I keep getting an exception:
Cannot access a closed file
The file is created just fine, but is empty (It should contain "Test string"). I can't understand how the file is closed unless some kind of garbage collection is doing away with it somehow??
The current code:
Function SaveFile(ByVal Type As ProfileType, ByVal suggestedFileName As String, ByVal saveAs As Boolean, ByVal writeData As String) As Boolean
Dim FileStream As Stream = Nothing
Dim FolderPath As String = Nothing
Dim CancelSave As Boolean = False
Dim SaveFileDialog As SaveFileDialog = New SaveFileDialog()
Try
If Type = ProfileType.Product Then 'Select the initial directory path
FolderPath = ProductPath
Else
FolderPath = ProfilePath
End If
If (FileName = String.Empty Or saveAs = True) Then 'If a file is not already selected launch a dialog to allow the user to select one
With SaveFileDialog
.Title = "Save"
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.DefaultExt = "xml"
.Filter = "Xml Files (*.xml)|*.xml"
.FilterIndex = 0
.FileName = suggestedFileName
.InitialDirectory = FolderPath
If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
FullyQualfiedPathName = New String(SaveFileDialog.FileName) 'Save the path and name of the file
FileName = Path.GetFileName(FullyQualfiedPathName)
Else
CancelSave = True
End If
.Dispose()
End With
End If
If (FileName <> String.Empty) Then 'Write the string to the file if the filewas correctly selected
FileStream = File.Open(FullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite) 'Open the file
Using FileStreamWriter As New StreamWriter(FileStream) 'Create the stream writer
FileStreamWriter.Write(writeData) 'Write the data
FileStream.Close() 'Clse the file
End Using
ElseIf (CancelSave <> True) Then 'Only throw an exception if the user *didn't* cancel the SavefileDialog
Throw New Exception("File stream was nothing", New IOException())
End If
Catch ex As Exception
MessageBox.Show(ex.Message & Environment.NewLine & FullyQualfiedPathName)
End Try
Return True
End Function
One problem I see is that you should be putting your File.Open in a Using block:
Using fs = File.Open(fullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Using writer As New StreamWriter(fs) 'Create the stream writer
writer.Write(writeData) 'Write the data
'fs.Close() <--- you do not need this line becuase the "Using" block will take care of this for you.
End Using
End Using
I'm not sure if this will resolve your issue because I can't run your code, but the Using block will automatically take care of closing and cleaning up disposable instances like FileStream and StreamWriter, even if an exception is thrown.
By the way, you should use proper naming conventions (lower camel case) for local variables.

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.

File is a directory not a file

I have a folder called test which has subfolders: A, B, and C at the root. I am trying to copy a file to these three folders.
Not sure why the I am getting the error:
The target file "c:\test\A" is a directory and not a file. Please help.
Dim OPUSINI As New FileInfo("C:\Program Files (x86)\OPUS_4.5\OPUS32.INI")
'Where is will be going
'Dim Win7DestLocation As String = "C:\Users"
Dim Win7DestLocation As String = "C:\test"
Dim WinXPDestLocation As String = "C:\Documents and Settings"
'Get a list of all the Subfolders within the Destination location
Dim Win7Destdir As New DirectoryInfo(Win7DestLocation)
Dim WinXPDestdir As New DirectoryInfo(WinXPDestLocation)
'Checks if Destination Exists for Windows 7
Dim Win7CheckExistDestLocation As New IO.DirectoryInfo(Win7DestLocation)
'Checks if Destination Exists for Windows XP
Dim WinXPCheckExistDestLocation As New IO.DirectoryInfo(WinXPDestLocation)
If Win7CheckExistDestLocation.Exists Then
Try
For Each subfolder As DirectoryInfo In Win7Destdir.GetDirectories
OPUSINI.CopyTo(subfolder.FullName, True)
Next
Catch ex As Exception
MessageBox.Show("Unable to backup Pump data files." + ex.ToString, "Backup Error:", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
You are passing a directory name to CopyTo.
That method wants a filename not a directory name.
Thus the exception received.
If I understand your code well, you need to change that line to
Dim destFile = Path.Combine(subfolder.FullName, OPUSINI.Name))
OPUSINI.CopyTo(destFile, True)
Also using DirectoryInfo objects is not really necessary here.
The simple Directory class could do the same things with less overhead

Copy files in VB.NET

I'm trying to create an installer-like application. Here is what its supposed to do: create a directory in C: and name it batch. Then copy the files from the folder and move it to the C:\batch directory. But the copying of files doesn't work.
How am I supposed to put the exact directory in here if that exact directory does not apply to all? What do I do with it? If the file that is to be copied is from: E:\Documents and Settings\Rew\My Documents\Visual Studio 2008\Projects\batch\batch
I want it to be universal. So that wherever the file maybe it could always copy it regardless of where it is located.
Somehow the creating of a directory work.
Dim FileToCopy As String
Dim NewCopy As String
Try
Directory.CreateDirectory("C:\Batch")
FileToCopy = "\batch\batch\ipconfigrenew.bat"
FileToCopy = "\batch\batch\ipconfigrelease.bat"
FileToCopy = "\batch\batch\ipconfigflushdns.bat"
NewCopy = "C:\Batch"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
MsgBox("File Copied")
End If
Catch
End Try
MsgBox("Done")
First, the only value in FileToCopy by the time you do the copy is the last one. I'm having trouble parsing the question to figure out what you need, but I would first do this:
Dim FileToCopy(3) As String
FileToCopy(0) = "\batch\batch\ipconfigrenew.bat"
FileToCopy(1) = "\batch\batch\ipconfigrelease.bat"
FileToCopy(2) = "\batch\batch\ipconfigflushdns.bat"
Dim NewCopy As String = "C:\Batch"
Dim s As String
For Each s In FileToCopy
If System.IO.File.Exists(s) = True Then
System.IO.File.Copy(s, NewCopy)
MsgBox("File Copied")
End If
Next
Next, I would decide if I needed to write this in a more generic way.