Visual Basic.NET Saving Preferences in a .txt or .ini - vb.net

I want to save my preferences for a program. I just want to know how to do it, since I cant get how to save this file at my documents, because every computer has a different name and username, but using the
My.User.Name
returns 'USERNAME-PC-USERNAME' which doesn't work.
For example, I want the program to create this text file 'CPreferences' at 'C:\Users\'username'\Documents'. And then when the program is re-opened it will automatically load this file into itself, the file will basically contain 2 lines:
Option1:<Value 1>
Option2:<Value 2>
The values will represent choices, ofcourse. So fundamentally, my question is:
1) How to save this file automatically at this user's documents WITHOUT showing a savefiledialog?
2) How to automatically load it if the file there exists?
Thanks,

VB.Net has built-in features for storing and retrieving the user's settings. Just use them. You won't have to worry about how the settings are stored or where the files are. It all just works.

Using something along the lines of string = "----------- " & CurrentTitle & " (" & Now.ToString() & ") User " & Environment.UserName & " on computer " & Environment.UserDomainName & "------------"
will result in
----------- Google - Google Chrome (3/12/2012 2:09:49 AM) User Drise on computer Drise-LAPTOP ------------
Using a streamwriter with filename "C:\users\" & Environment.UserName & "..." should do the trick.
To auto-load the file, check if the file exists and use a streamreader with the same path variable as above, or if not, then set default settings.

For saving to the "My Documents" folder for the current user, this will return the directory path:
My.Computer.FileSystem.SpecialDirectories.MyDocuments
You can also use other items in "special directories" if you want things like the "downloads" or "my pictures" folders, or anything else like that.

I think what you're looking for is user configuration.
You can store settings for users that will be unique to the logged in user.
Use this as a reference for getting started with it:
http://www.codeproject.com/Articles/12252/Application-settings-in-VB-NET-2-0-and-Visual-Stud

Related

MS Project can't change filname bevor save

I have the following question:
It seems that I cannot change the name of a project file before it is saved. The following code does not work. Does anyone have a better idea? I am using Project 2016
DateToday = Format(Now, "YYYY-MM-DD")
Set Test = Application.Projects.Add(False, PTP_Template, False)
Test.Name = DateToday & " SomeMoreTest"
Test.SaveAs
I would like to change the file name so that users already have the correct file name in the file save dialog.
Thanks for any suggestion
It seems that I cannot change the name of a project file before it is
saved.
That is correct. The Project Name property is read-only just as it is with Excel, Word, etc.
The way around this would be to create a macro to save the file for the user. So instead of the user going to File: Save As, they would need to run the macro.

VBA - Finding folder inside a directory and returning the path of that folder

I am using excel vba to make an application that acts as a job card. User will fill in relevant fields, press a button to update a running summary of costs, as well as generate a printable pdf of the job card. I have very limited experience in coding (a semester of java 4 years ago) so i am relatively new to this.
Currently, the application automatically updates the summary file and can open a word template file and fill it in with information from the input fields, so it mostly works. I have realised an issue in the way it is finding the summary files, in that as soon as a folder name does not align with the way i am constructing the folder paths in the app, it will return errors.
At the moment I am going into folders like this:
templatePath = "C:\SERVICE\Card Template.doc"
If cbxType.Text = "Plant" Then
savePath = "C:\SERVICE\0.1 PLANT\" & cbxNo.Text & " - " & txtMakeModel.Text & " " & txtRego.Text & "\0.2 SERVICE SHEETS\"
ElseIf cbxType.Text = "Vehicle" Then
savePath = "C:\SERVICE\0.2 VEHICLES\"
End If
The directory is constructed from text and combo boxes which are populated once the user chooses a type (plant, vehicle, etc.) and then ID, which fills in boxes for model name, registration number, hours etc.
I am after a piece of code that can iterate through a given directory, searching the folder names for a string and returning the path of that folder. Each folder begins with the ID number, so I figure I can search folder names for that but I am not sure how to construct the loop. Any help with this, or alternative ideas would be appreciated. If it isn't too much to ask I'd also like a little bit of an explanation on how it works.

Cannot delete file because it is being used by another process - VB.net

I am converting an TIFF file to a .PNG file in vb.net. First, I save the TIFF file to a specific location (given by NewFileName). Then I convert the file to .PNG using the Bitmap.Save method. Later in my program, I attempt to delete all the .tif files. However, I get an error that says the files are still in use. I have done some research about the reasons for this and I have read that a lot of the errors come from not closing filestream. However, I do not use filestream in my program so I think it is something else. Another possibility that was suggested was that the file was opened twice. I have scoured my code and I am pretty sure the files were never opened, only saved and accessed with the bitmap.Save command. I also downloaded handle.exe and process explorer to find which process was locking the files. Apparently, the files are only in use by the program once I convert them to PNG using the bitmap.save command. Maybe there is a way to close bitmap.Save? Any other suggestions of what to add would be appreciated as well.
objApplication.StartCommand(SolidEdgeConstants.AssemblyCommandConstants.AssemblyViewBottomView)
view = window.View
view.Fit()
withoutExt = "C:\Folder" & "\" & shortForms(12) & FileName
NewFileName = withoutExt & ".tif"
view.SaveAsImage(NewFileName, Width:=width, Height:=height, Resolution:=resolution, ColorDepth:=colorDepth)
System.Drawing.Bitmap.FromFile(NewFileName).Save(withoutExt & ".png", System.Drawing.Imaging.ImageFormat.Png)
Thanks in advance!
I figured it out. All you need is a using statement so that NewFileName is released before I delete it. I changed the code to this and it worked:
view = window.View
view.Fit()
withoutExt = ChosenFile & "\" & shortForms(13) & FileName
NewFileName = withoutExt & ".tif"
view.SaveAsImage(NewFileName, Width:=width, Height:=height, Resolution:=resolution, ColorDepth:=colorDepth)
Using tempImage = System.Drawing.Bitmap.FromFile(NewFileName)
tempImage.Save(withoutExt & ".png", System.Drawing.Imaging.ImageFormat.Png)
End Using
My.Computer.FileSystem.DeleteFile(NewFileName)
Thanks everyone for your help!

UnauthorizedAccessException with File.AppendAllText in VB.NET

I have recently started getting System.UnauthorizedAccessException errors when using File.AppendAllText to write to a shared drive on the network. I think there were some changes to the network when this happened. The code in my application hasn't changed.
I have asked our IT dept to grant me full permission to the folder. I can see I have permissions for Modify, Read & Execute, Read, Write under my username if I navigate to the file and look at the Security tab under properties. I am also part of a group with read, write and modify permissions to the folder.
This works without error in the same folder:
File.WriteAllText(myFile, myText)
This generates a System.UnauthorizedAccessException error when it reaches the AppendallText:
If File.Exists(myFile) = False Then
' Create a file to write to.
Dim createText As String = logTime & " " & report_data
File.WriteAllText(myFile, createText)
Else
Dim appendText As String = logTime & " " & report_data
File.AppendAllText(myFile, appendText)
End If
I have tried deleting the file and creating it again, that made no difference.
I tried File.SetAttributes(myFile, FileAttributes.Normal)
The IT dept can't see what the problem is.
I can manually open, change and modify the file. The problem only arises if I am trying to do this programmatically.
Is there a different 'user' which tries to modify files? Could the file be open somehow, or would that generate a different error?
I'm using VB.NET 2012, .net framework 4.5, Windows 8.1
The network changes were the problem. It doesn't seem possible to resolve this as it is. Instead I made a copy of the text data, append my new text to that, delete the file, and save the updated text to a new file.

Visual Basic in Word 2010 - Open Dir - Relative Path

I'm creating a word document and I'm having trouble working out the code to open a specific directory.
Basically, I'll have a bunch of video files on a USB drive or a DVD in separate folders and when the command button is clicked, I would like it to open the relevant directory in a windows explorer window.
I did some Google searching and came up with the following code:
FolderName = "c:\windows"
TaskID = Shell("explorer.exe " & FolderName, vbNormalFocus)
The only problem now is that I need to change the path reference from absolute to relative, as I'll be running everything from either a USB drive or a DVD on multiple computers.
I have tried every possible iteration of relative path references, but I can't seem to get it to work. The folders are simply sub-directories of where the word document is.
Anyone got any clues as how I can change the above code to be relative rather than absolute path references?
I think something like this might be what you're looking for:
FolderName = ActiveDocument.Path & "\SubFolder"
TaskID = Shell("explorer.exe " & FolderName, vbNormalFocus)
Assuming that your document is the active one, otherwise you might need to search through the Documents collection for the correct one.