Open Word Document From Dynamic Directory VB.Net - vb.net

I have a program for which I have developed a user guide. I have placed this user guide within the project directory. I created a MenuStrip Item by which to open the user guide in Word on the user's machine. I was successfully able to do this with the following code:
Try
userGuide = MSWord.Documents.Open("C:Users\administrator\Documents\VisualStudio2010\Project3\UserGuide.doc")
MSWord.WindowState = Word.WdWindowState.wdWindowStateNormal
MSWord.Visible = True
Catch ex As Exception
MsgBox("An error has prevented the document from opening. The document may not be available." & vbCrLf & vbCrLf & _
"Please try one of the following options:" & vbCrLf & _
"- Check to see if the document is already open" & vbCrLf & _
"- Restart the program")
End Try
The problem is, the path used to open the file will not exist on the users machine. This is a standalone system, so no file share can be created in which to place the document, therefore no common path can be coded.
Is there a way to code dynamic paths? Perhaps something like:
userGuide = MSWord.Documents.Open("%windir%\UserGuide.doc")
Thanks!

if the document will be stored relative to the install path of the application executable, then start with the path of the exe:
Dim path As String
path = System.IO.Path.GetDirectoryName( _
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
Dim docPath as String;
docPath = Path.Combine(path,"UserGuide.doc");

Related

Trying to save a pdf file of a screenshot of the form, given a specified location from the user's input

I am trying to save a created, PDF file to a location specified by the user. I'm using Visual Studio Community 2019. Essentially, I am taking a screenshot of this form:
And by using the PdfSharp external library, I create a PDF file and then save that PDF to some file location specified by the user. Here is the UI for the user to select their preferred file location:
The issue arises once the program tries to save the PDF file to the location given by the user. Here is the error I get from Visual Studio:
System.NotSupportedException: 'No data is available for encoding 1252. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.'
I looked online for this specific error, but I don't really understand it nor what to do with it, it's very confusing. I'm still a bit of beginner when it comes to working with Visual Basic. Here's the code that tries to do it:
Dim fileLocation As String
fileLocation = folderBrowseBox.Text
GetFormImage(True).Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg", ImageFormat.Jpeg)
' Create new pdf document and page
Dim doc As New PdfDocument()
Dim oPage As New PdfPage()
' Add the page to the pdf document and add the captured image to it
doc.Pages.Add(oPage)
Dim img As XImage = XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")
'Create XImage object from file.
Using xImg = PdfSharp.Drawing.XImage.FromFile(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod) & ".jpg")
'Resize page Width and Height to fit image size.
oPage.Width = xImg.PixelWidth * 72 / xImg.HorizontalResolution
oPage.Height = xImg.PixelHeight * 72 / xImg.HorizontalResolution
'Draw current image file to page.
Dim xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(oPage)
xgr.DrawImage(xImg, 0, 0, oPage.Width, oPage.Height)
End Using
doc.Save(fileLocation & "\" & RemoveWhitespace(filename) & "_" & RemoveWhitespace(collectionPeriod))
img.Dispose()
The second to last line of code ("doc.Save(fileLocation & ...)") is where the error occurs. The folderBrowseBox.Text (very first line of code) comes from the textbox you see from my second screenshot. Any help/advice will be greatly appreciated!
Try adding this line before writing the PDF file
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance)
Got the idea from here

VBA - Open a folder on Mac

I simply want to open a folder by VBA. I've tried the following code but it does nothing.
For Windows I know the following command is working fine
Call Shell("explorer.exe " & filepath, vbNormalFocus)
This is the code I am using...
Sub Open_Folder_On_Mac()
Dim folderPath As String
Dim RootFolder As String
Dim scriptstr As String
On Error Resume Next
RootFolder = MacScript("return (path to desktop folder) as String")
scriptstr = "do shell script ""open " & RootFolder & """"
MacScript (scriptstr)
End Sub
Can you help me, getting the code for simply opening a folder on a Mac? Thanks!
AppleScript does these kinds of things by telling a particular application to perform one or more of the commands exposed in the scripting dictionary (if any) provided by the application developer. In the case of the Finder (which runs at all times), It would be:
tell application "Finder" to open theFolder
where theFolder is an alias, file, or POSIX file object, for example from:
set theFolder to (choose folder)
Note that the open shell utility is normally used to open files and applications.
Untested examples:
The older (deprecated) style:
• Note that this command may not work in a sandboxed application.
Dim ScriptString as String
Dim FolderPath as String
ScriptString = "tell application " & Chr(34) & "Finder" & Chr(34) & " to open folder (path to desktop)"
-- or --
FolderPath = "Macintosh HD:Users:you:Path:To:Some:Folder:"
ScriptString = "tell application " & Chr(34) & "Finder" & Chr(34) & " to open folder " & FolderPath
MacScript(ScriptString)
The newer (2016+) style:
• Create a script using the Script Editor that contains the handlers (subroutines) you want to call, for example:
on openFolder(folderPath)
tell application "Finder" to open folder folderPath
end openFolder
• Place the script in your user's ~/Library/Application Scripts/[bundle id] folder, where [bundle id] is the bundle identifier of the application using the script.
• The new command is in the form AppleScriptTask("script file name.scpt", "handler name", "handler argument"), for example:
Dim FolderPath as String
FolderPath = "Macintosh HD:Users:you:Path:To:Some:Folder:"
AppleScriptTask("MyScript.scpt", "openFolder", FolderPath)
See Run an AppleScript with VB.

Open a file in a new instance of program

All;
I have a bit of code I've written that opens a design blueprint when I scan a bar code. It works well enough, but I'd like to open a new instance of the design software (Solidworks) and have the print display in the new instance. Right now, no matter how many Solidworks instances I have open, the print will only open in the first instance started.
The line commented out below is the line that works, just not in the right instance. The line below that is what I'd expect to work, but it returns a 'file not found' even though the path to solidworks and the print path are both correct.
Any explanation as to why this isn't working would be much appreciated as I'm obviously very new at this...and have no idea what I'm doing.
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim barcode As String = tb_barcode.Text
Dim filename As String = tb_barcode.Text
'Add File Extension to end of path
Dim ext As String = ".SLDDRW"
'Split job number from detail number in barcode textbox
barcode = Split(tb_barcode.Text, ".")(0)
filename = Split(tb_barcode.Text, ".")(1)
'- This works, just in primary instance
'System.Diagnostics.Process.Start("G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext)
'- This does not work
System.Diagnostics.Process.Start("'C:\Program files\Solidworks Corp\Solidwork\SLDWORKS.exe' 'G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext + "'")
Catch
MessageBox.Show("File Not Found")
End Try
End Sub
Sorry for naive approach but shouldn't there be a comma in Process.Start between 2 arguments?
Start(String, String)
Starts a process resource by specifying the name of an application and a set of command-line arguments, and associates the resource with a new Process component. docs
Why don't you use the Application.ExecutablePath.That returns the Application's path with its full name. Then your code should be
System.Diagnostics.Process.Start(Application.Executablepath, "G:\Fixtures\" & barcode & "\Details\" & barcode & " DET " & filename & ext + "'")
Also make sure that the second string argument is a valid path.

VB.NET %appdata% path access is denied

I want a folder to be created inside user's %appdata% folder, it does create, but it cannot write a file inside the folder, it says "Access denied", I googled it, but nothing worked for me.
Dim SpecialAppData As String = GetFolderPath(Environment.SpecialFolder.ApplicationData)
Dim CLOUDSAVEDFILESCFG As String = SpecialAppData & "\da_dev\clientsettings\cloud\"
If System.IO.Directory.Exists(SpecialAppData & "\da_dev\clientsettings\cloud\") Then
Else
System.IO.Directory.CreateDirectory(SpecialAppData & "\da_dev\clientsettings\cloud\")
End If
timeout(0.5)
Dim objWriterCSF As New System.IO.StreamWriter(CLOUDSAVEDFILESCFG)
TextBox1.Text = My.Settings.username
TextBox2.Text = My.Settings.password
If My.Computer.FileSystem.FileExists(SpecialAppData & "\da_dev\clientsettings\cloud\" & "files.cfg") Then
Else
objWriterCSF.Write("0")
objWriterCSF.Close()
End If
The error is:
EDIT:
I noticed the picture says that it cannot find path, I fixed that, but now I get the issue:
You can not "open a file" that is actually a directory.
Dim CLOUDSAVEDFILESCFG As String = SpecialAppData & "\da_dev\clientsettings\cloud\"
CLOUDSAVEDFILESCFG points to a directory.
The error here is not that access is denied, but that the directory does not exist. You can use Directory.CreateDirectory(Path.GetDirectoryName(CLOUDSAVEFILESCFG)) to ensure that the directory exists before trying to create a file within it.
Solved:
Forgot to add a file behind CLOUDSAVEDFILESCFG...
Like this:
Dim objWriterCSF As New System.IO.StreamWriter(CLOUDSAVEDFILESCFG & "\files.cfg")

Download File and Extract Immediately - File is being used by another process

I'm looping through a list of zip files and downloading them from a WebClient. I'm trying to extract them immediately after they download, but getting an error that the file is being used by another process.
Error: The process cannot access the file 'c:\temp\test.zip' because it is being used by another process.
The only thing that I can think of is that maybe the file is still "in use" for a short time after being downloaded? DownloadFile does block ("This method blocks while downloading the resource." - http://msdn.microsoft.com/en-us/library/ez801hhe(v=vs.110).aspx), so I can't see it being an issue with the file still downloading.
Any ideas on a workaround?
Using client As New WebClient
oLog.Info("Downloading " & strFileServer & " to " & strFileLocal & "...")
If Not Directory.Exists(strPathLocal) Then Directory.CreateDirectory(strPathLocal)
client.DownloadFile(strFileServer, strFileLocal)
End Using
Using archive As ZipArchive = ZipFile.OpenRead(strFileLocal)
For Each entry As ZipArchiveEntry In archive.Entries
oLog.Info("Extracting " & entry.FullName & " to " & strPathLocal & "...")
entry.ExtractToFile(strFileLocal, True)
Next
End Using