i'm using fileopen() function to open the file, after doing all the works i'm using fileclose() to close the file. but when i access the file again it returns already the file is opened by another process.
sample:
Dim intFile As Integer = FreeFile()
FileOpen(intFile, mstrFilename, OpenMode.Binary, OpenAccess.Read, OpenShare.LockWrite)
FileClose(intFile)
Thanks!
I think you could use the System.IO.File class for all file operations.
Sample:
var fs = File.OpenWrite();
var info = new UTF8Encoding(true).GetBytes("Test of the OpenWrite method.");
fs.Write(info, 0, info.Length);
fs.Close();
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.
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.
Using Visual Studio 2013
I have been attempting to copy an audio .wav file from a vb.net Windows Form Application to no avail. I have attempted a few methods:
File.Copy(My.Resource.click1, "c:\destination folder", True)
I have tried calling a Sub
Dim ms As New MemoryStream
My.Resources.click1.CopyTo(ms)
Dim ByteArray() As Byte = ms.ToArray
sfr(toPath2 & "\click1.wav", ByteArray)
Public Sub sfr(ByVal FilePath As Byte, ByVal File As Object)
Dim FByte() As Byte = File
My.Computer.FileSystem.WriteAllBytes(FilePath, FByte, True)
End Sub
I have also tried
File.WriteAllText(toPath2 & "\click1.wav", My.Resources.click1)
How does one copy an audio resource to the hard drive?
Here is a VB.Net version of the tested C# version:
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim file As String = String.Format("{0}.click1.wav", asm.GetName().Name)
Dim fileStream As Stream = asm.GetManifestResourceStream(file)
SaveStreamToFile("c:\Temp\click1.wav", fileStream) '<--here is the call to save to disk
Public Sub SaveStreamToFile(fileFullPath As String, stream As Stream)
If stream.Length = 0 Then
Return
End If
' Create a FileStream object to write a stream to a file
Using fileStream As FileStream = System.IO.File.Create(fileFullPath, CInt(stream.Length))
' Fill the bytes[] array with the stream data
Dim bytesInStream As Byte() = New Byte(stream.Length - 1) {}
stream.Read(bytesInStream, 0, CInt(bytesInStream.Length))
' Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length)
End Using
End Sub
+1 on detailing your attempts before posting, let me know how you go.
Here is the Code Nice And Easy :
Dim FilePath AS String = Application.StartupPath + "\From_Resource.wav"
IO.File.WriteAllBytes(FilePath,My.Resource.click1)
and then you can check if it exists :
If IO.File.Exists(FilePath) Then MsgBox("File Exists")
and one more trick , Play it in Default Player :
Process.Start(FilePath)
Thank you all for your suggestions. This is what I came up with to perform the task that I needed.
Dim ms As New MemoryStream
My.Resources.click1.CopyTo(ms)
Dim AudioFile() As Byte = ms.ToArray
File.WriteAllBytes(toPath2 & "\click1.wav", AudioFile) '<-- toPath2 is a specific folder I am saving to
ms.Close()
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.
I am making an encryption program that also functions as a notepad (CryptoMatic). There is a Open function with the following code:
Dim r As New StreamReader(filename)
Dim text As String = r.ReadToEnd
txtFileContents.text = text
r.Dispose()
r.Close()
Now there is the save and save as button
the save button checks if the file had been saved previously or not. If yes then I am trying to write to that file with the following code:
Dim myFileStream As New System.IO.FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None)
myFileStream.Lock(0, 100)
Dim myWriter As New System.IO.StreamWriter(myFileStream)
myWriter.WriteLine(text)
myWriter.Flush()
myWriter.Close()
myFileStream.Close()
myFileStream.Unlock(0, 100)
Now when i press the save button it gives the following error:
The process cannot access the file 'C:\Users\VisualTech\Documents\Visual Studio 2010\Projects\CryptoMatic Update\CryptoMatic Update\bin\Debug\text.txt' because it is being used by another process.
and the application stops, can anyone please help me?
I have tried your code above and have noticed two things:
You don't need a myFileStream.Lock call because you already open it
with FileShare.None
You can't call myFileStream.Unlock(0, 100) after the call to
myFileStream.Close()
So I have rewritten your code in this way.
Sub Main
Dim text = "This is a text to write in the stream"
Using myFileStream As New System.IO.FileStream("D:\temp\testlock.txt", FileMode.Append, FileAccess.Write, FileShare.None)
Using myWriter As New System.IO.StreamWriter(myFileStream)
myWriter.WriteLine(text)
End Using
End Using
End Sub