File.Create(path) error VB.NET - vb.net

Hi i've used the code bellow successfully at the beginning but i don't know what i did so it stopped creating the file MessageIO.dat under the folder (ProgramFiles)\UniWin Activator Data
i used this code: (result: created only folder UniWin Activator Data)
Dim UniWinPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UniWin Activator Data")
Directory.CreateDirectory(UniWinPath)
Dim MsgIO = Path.Combine(UniWinPath, "\MessageIO.dat")
File.Create(MsgIO)
and used this: (result: error at the command File.Create)
Dim UniWinPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UniWin Activator Data\MessageIO.dat")
File.Create(UniWinPath)
and used this: (result: nothing happened)
Dim UniWinPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UniWin Activator Data")
Dim MsgIO = Path.Combine(UniWinPath, "\MessageIO.dat")
File.Create(MsgIO)
what's the way to create that file? (I have admin rights already)

The first of your code is perfectly fine. Just change Dim MsgIO = Path.Combine(UniWinPath, "\MessageIO.dat") to Dim MsgIO = Path.Combine(UniWinPath, "MessageIO.dat"). (Remove the backslash). Path.Combine automatically adds one. And as always, to access special directories, make sure you have Administrator Privilleges. The reason the last two codes aren't working is that File.Create creates a file in an existing directory. It can't create the directory itself.

When combining paths, you should not specify the "\" char at begining of the second path item as this will mean the root path!
for example, Path.Combine("D:\Folder1", "\MessageIO.dat") will result "\MessageIO.dat". but you have to write Path.Combine("D:\Folder1", "MessageIO.dat") which will return "D:\Folder1\MessageIO.dat"
Note: in windows 7 or above, access to special folders like as Program Files require special permissions! check that your app has such permission. (you can test for other norman folder first to ensure other parts of your code is ok)

Related

Grabbing current user.config path (Visual Basic)

Is there a way of grabbing the location of the My.Settings user.config location? So for example I want to be able in VB to grab the path of the user.cofing file path to a string
The reason I ask is that I have an application where the user.config file is backed up and then restored, the issue is that with the my.settings folder structure it uses a unique hash with the folder name meaning that I cannot write into the code a static folder path, instead I need to be able to grab the location of the user.config OR be able to get the folder name of the application AppData.
Any ideas?
To put this in perspective, currently I'm using something like this:
Dim filePath As String
filePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\My_App\My_App.exe_Url_<the_hash_that_changes_causing_issues>\1.0.0.0\user.config"
Because of the hash change this will not always work
Try executing this code:
Dim mainConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim userConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming)
Dim userLocalConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
Console.WriteLine(mainConfig.FilePath)
Console.WriteLine(userConfig.FilePath)
Console.WriteLine(userLocalConfig.FilePath)
You'll need to reference System.Configuration.dll and import System.Configuration.

Solidworks EPDM 'Get latest' from VBA

Due to a company policy on how the PDM system operates, when the user checks in a file, the local copy is deleted from the users cache. My macro checks files out, edits them and checks back in again. If I try and edit a file that has just been edited I get a 'file not found' error (because it's been deleted from cache). I have tried to get around this by writing a sub to get the latest copy of a file immediatly before editing it to ensure there is always a file present but the code doesnt seem to retrieve the file. The sub is as below.
Sub GetLatest(fName As String)
Dim vaultName As String
Dim eVault As IEdmVault13
Dim eFile As IEdmFile8
Dim BG As IEdmBatchGet
Dim files(1) As EdmSelItem
'log into the vault
vaultName = Config.ReadXMLElement(pathConfig, "vaultname")
Set eVault = New EdmVault5
If Not eVault.IsLoggedIn Then
Call eVault.LoginAuto(vaultName, 0)
End If
'get the file to get lastest
Set eFile = eVault.GetFileFromPath(fName)
'put the file in an array
files(0).mlDocID = 0
files(0).mlProjID = eFile.ID
Set BG = eVault.CreateUtility(EdmUtil_BatchGet)
Call BG.AddSelection(eVault, files())
Call BG.CreateTree(0, EdmGetCmdFlags.Egcf_SkipExisting)
Call BG.GetFiles(0, Nothing)
End Sub
If I manually 'get latest' in the EPDM browser before editing the file, the macro reads it fine. The code is slightly modified from that posted by Michael Dekoning at https://forum.solidworks.com/thread/51105
From first glance, it looks like you are populating the EdmSelItem properties incorrectly.
The docID property is the database ID of the document. The ProjID property is the ID of the containing folder. For getting the latest version, you can use any containing folder, as it will be checked out in all folders. With EPDM, when a file is "shared" it can have multiple parent folder IDs it belongs to, and we can enumerate over then using the methods from iEdmFile5 GetFirstFolderPosition and GetNextFolder.
You can refer to the documentation for further information and examples.
If you want to get a single file, try the following adjustment and see if that does it:
Set eFile = eVault.GetFileFromPath(fName)
Dim eFolder as iEdmFolder5
Dim Pos as iEdmPos5
Set Pos=eFile.GetFirstFolderPosition
Set eFolder=eFile.GetNextFolder(Pos)
'Get the file from the folder
files(0).mlDocID = eFile.ID
files(0).mlProjID = eFolder.ID
When you provide DocID = 0 it tells EPDM to get all the files in the folder specified. Like so:
'Get all files from the folder
files(0).mlDocID = 0
files(0).mlProjID = eFolder.ID

Visual Basic: File is said to be in the wrong folder

Ok, here is my story:
I am building a fileviewer, and i am trying to delete the selected file in the listview.
when i try to delete it, it gave me an error saying the file wasnt found. I looked at my desktop and the file was there. here is the original code:
dim f as string = lv1.focuseditem.text
my.computer.filesystem.deletfile(f)
lv1.update()
this gave me that error. My updated code is supposed to show me where the computer thinks my file is:
Dim file As String = lv1.FocusedItem.Text
Dim testFile As System.IO.FileInfo
testFile = My.Computer.FileSystem.GetFileInfo(file)
Dim folderPath As String = testFile.DirectoryName
MsgBox(folderPath)
this shows a messagebox that shows the path of:
C:\Users\tgs266\Desktop\SIOS\SIOS\SIOS\obj\Debug\test.txt
but the real file location is:
C:\Users\tgs266\Desktop\test.txt
please help
How are you getting the filenames for the ListView? Is it just the filename and no path?
If, for example, lv1.FocusedItem.Text is "test.txt", and that is the value you use (without the path), by default the program will look in the directory it's executing in. This is most likely why you're seeing C:\Users\tgs266\Desktop\SIOS\SIOS\SIOS\obj\Debug\test.txt as the location, instead of what you expected.
If all the files are on your desktop, you can use Environment.GetFolderPath in conjunction with the Environment.SpecialFolder Enumeration to get the file, like this:
Dim file As String = lv1.FocusedItem.Text
Dim testFile As System.IO.FileInfo
testFile = My.Computer.FileSystem.GetFileInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\" + file)
Dim folderPath As String = testFile.DirectoryName
MsgBox(folderPath)
However, if you're going to have files scattered throughout your system, you'd be better off storing the full path as #Plutonix indicates in his comment.
It looks like your code is looking in your applications path on the server while you want to look at the users desktop location.

How do I get a text file to be a part of my build?

I wrote a program that reads from text files and can create them to load and save data. I have a few files that are the "default" data that are loaded as soon as the program start. The files are loaded by a static reference. My code runs fine before I publish it, but obviously when I publish it, the static references no longer work. I don't know how to add the default data to the build as distinct text files so that I can still reference it after the build.
I imagine being able to build the program and have some sort of folder that accompanies the executable with the default data files in them that I can easily reference, but I don't know how to do that (or if there is a better way).
Below is the start of the code I use to read from the file. Currently, the default data's file name is passed statically into the sub and is used to identify the file to read from, so I'd like to have a published file that I can do the same thing with.
Try
Dim sr As New IO.StreamReader(FileName)
Dim strLine As String = ""
Do Until sr.EndOfStream
strLine = sr.ReadLine
'Code that interprets the data in the file
Note: I've tried adding the files as "Resources" but I can't seem to reference the file as a text file; I can only retrieve the massive wall of text contained within the document which won't work with the above code (unless of course I'm missing something).
If you could clarify:
How do I add a file to a build so that I can still access it
collectively by a file name?
How will my code reference the files (e.g. by
"My.Resources.filename"?) in the final build?
You can add the file to the build as either a content file or an embedded resource.
For a content file, set the Build Action of the file to 'content', and Copy to Output Directory to 'Copy Always' in the file properties. You can then access the file like this:
FileName = Application.StartupPath() = + FileName
Dim sr As New IO.StreamReader(FileName)
...
To embed the file as a resource you have to set the Build Action of the file to 'Embedded Resource' and Copy to Output Directory to false.
This Microsoft support page has a walkthough about accessing embedded resources. The code would be something like this:
Dim sr As StreamReader
Dim thisAssembly As Assembly
thisAssembly = Assembly.GetExecutingAssembly()
sr = New StreamReader(thisAssembly.GetManifestResourceStream("NameSpace." + FileName))
Dim strLine As String = ""
Do Until sr.EndOfStream
strLine = sr.ReadLine
'Code that interprets the data in the file
...
Replace NameSpace with the namespace of your application (Project Properties -> Application -> root namespace)
You also have to add Imports System.Reflection at the top of your code file.
Using an embedded resource has the advantage of less files to manage, and you don't have to keep track of paths.

How to specify a path with spaces for StreamWriter

In VB.Net, how do I provide the StreamWriter constructor with a path that includes spaces? StreamWriter("""C:\Users\Public\Public Users\file.txt""") does not work.
Here is a working code example:
Dim fs As New System.IO.StreamWriter("e:\test 123.txt")
fs.Write("hello")
fs.Close()
UPDATE:
The new example for folder with space(s):
'this is your filename
Dim Filename As String = "e:\folder with space\test 123.txt"
'this is your folder
Dim Folderpath As String = System.IO.Path.GetDirectoryName(Filename)
'now do checking if the folder exists, if not create the folder
If System.IO.Directory.Exists(Folderpath) = False Then
System.IO.Directory.CreateDirectory(Folderpath)
End If
'now create the file as usual
Dim fs As New System.IO.StreamWriter("e:\folder with space\test 123.txt")
fs.Write("hello")
fs.Close()
The reason for your code didn't compile because you have not create the folder before creating the file, ie that folder must be existed before you can create your file.
You don't put quotes around the string you pass to the StreamReader constructor. Quotes are only used when you use, say, the command line. Or anything else that uses spaces as separators between arguments. The program requires those double quotes to recognize an argument with an embedded space.
Not necessary here, there's no ambiguity since the argument only takes the path to a single file. The only exception to that rule that I know of is the ProcessStartInfo.Arguments property.
So, just put single double quotes around the string, the syntax that the compiler requires. Your real problem is the name of the folder. Windows Explorer shows a different name for the folders in c:\users\public. For example c:\users\public\videos is displayed in the Explorer window as "Public Videos". It's trying to be helpful by expanding the abbreviated name. Your program however has to use the real folder name. Which is probably "users", not "Public Users". To find out for sure, use the command line (cmd.exe). Use cd \users\public and dir /a.
Last but not least, that folder has a different name on different versions of Windows. You should use Environment.GetFolderPath(). "Public Users" isn't a standard folder name however, not sure why you are using it.