How to use RichEditBox in Visual Basic to save the file? - vb.net

I want to save whatever is being typed in RichEditBox. Below is my example. I was able to successfully with TextBox by using "mytext.Text" but there is no such option that I could see of RichEditBox.
Private Async Function Button_Click(sender As Object, e As RoutedEventArgs) As Task
Dim savePicker As New FileSavePicker
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
' Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add(".txt", New List(Of String) From {".txt"})
' Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document"
Dim file As StorageFile = Await savePicker.PickSaveFileAsync
If file IsNot Nothing Then
' Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync
CachedFileManager.DeferUpdates(file)
' Write to file
Await FileIO.WriteTextAsync(file, txtfile.)
' Let Windows know that we are finished changing the file so the other app can update the remote version of the file.
' Completing updates may require windows to ask for user input
Dim status As FileUpdateStatus = Await CachedFileManager.CompleteUpdatesAsync(file)
End If
End Function

Assuming a Windows.UI.Xaml.Controls.RichEditBox, you can retrieve the text with the GetText method of the control's Document property. You can also write the document directly to a stream with the SaveToStream method of the Document property.

Related

How to dynamically get path to HTML file in VSTO project for Outlook add-in

I am creating a simple Outlook 2016 add-in that will allow the users create a new mail message based on a HTML template.
I have created a Ribbon and added a button to it. Here is the click event handler code:
Private Sub btnCreateMail_Click(sender As Object, e As RibbonControlEventArgs) Handles btnCreateMail.Click
Dim app As Application = Globals.ThisAddIn.Application
Dim currentAccount As Account = app.Session.Accounts.Item(1)
Dim mailItem = DirectCast(app.CreateItem(OlItemType.olMailItem), MailItem)
mailItem.SendUsingAccount = currentAccount
mailItem.To = currentAccount.DisplayName
mailItem.BCC = IdentifyContacts()
mailItem.BodyFormat = OlBodyFormat.olFormatHTML
mailItem.Importance = OlImportance.olImportanceLow
mailItem.HTMLBody = GetEmailBody()
mailItem.Subject = "Subject"
mailItem.Display(False)
End Sub
GetEmailBody() function is responsible for reading the template and modify placeholders as required:
Private Function GetEmailBody() As String
Dim strEmailBody As String
Const strTemplatePath = "C:\Users\umute\template.htm"
' Read the template
Using reader As New StreamReader(strTemplatePath)
strEmailBody = reader.ReadToEnd
strEmailBody = strEmailBody.Replace("{TodaysDate}", Date.Now.ToString("dddd dd MMM yyyy"))
strEmailBody = strEmailBody.Replace("{Name}", GetCurrentUser())
strEmailBody = strEmailBody.Replace("{Greeting}", DetermineGreeting())
reader.Close()
End Using
Return strEmailBody
End Function
The above code works perfectly, however, I am not sure how to get the path to the template file dynamically, that is without entering the full path including C:\Users\ etc. This is because I would like to ship the template file with the add-in to avoid relying on the user to keep it in their local hard drive.
I know that in ASP.NET it is possible to use Server.Mappath("~/file.html") to accomplish this but I don't know the equivalent of this when writing an add-in for Outlook.
After hours of trying, I figured out that the correct way to reference a file is to add it as a resource.
I added a new item of type Resource to the project and added the html template to it. Then, accessed the file like this:
Dim strEmailBody As String = My.Resources.AllResources.Template

Upload and replace the same image file if it already exist

I have a picturebox named PB_Company_Logo and I have a button named btn_Save and within this button I have this function which saves the image in PB_Company_Logo to current_directory/images
Public Sub save_PB(PB_Name As PictureBox)
Dim filename As String = "company_logo.png"
Dim path As String = Directory.GetCurrentDirectory() & "\images"
Dim filename_path As String = System.IO.Path.Combine(path, filename)
If (Not System.IO.Directory.Exists(path)) Then
System.IO.Directory.CreateDirectory(path)
PB_Name.Image.Save(filename_path)
Else
PB_Name.Image.Save(filename_path)
End If
End Sub
The problem is, there are cases where the user will upload a new company_logo.png. I want the system to treat the uploading of new image as replacing the former company_logo.png.
I think the error in this line of code means that the file is currently in used (locked) and therefore cannot be replaced.
Else
PB_Name.Image.Save(filename_path)
End If
When you load a pictureBox control with an image file the ide (vs) puts a lock on the file. This happens when you set the image property of the pictureBox control to a file at design time.
You can use the FileStream object.
Example:
Dim fs As System.IO.FileStream
' Specify a valid picture file path on your computer.
fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
After you have done the workaround you can then use the System.IO.File.Exists(img) namespace to check wether or not a picture exists.
Example: This checks if the image passed through already exists and if it does then it will replace it.
Dim imageStr As String = "~/images/name.jpg"
If System.IO.File.Exists(imageStr) Then
Image1.ImageUrl = "~/images/name.jpg"
End If

How do I specify relative file path in VB.net

I have a Webbrowser control in a form which displays a pdf file. I have to specify the URL as the file location on my computer.
eg.
E:\Folder\Manual.pdf
Both the pdf file and the program are in the same folder.
How do I specify the URL so that when I move the folder onto another drive, it opens the same pdf file?
The location of your application is
Dim path as String = My.Application.Info.DirectoryPath
The you could use:
Dim pdffile as String = IO.Path.Combine(path, "pdffile.pdf")
WebBrowser1.Navigate(pdffile)
If I understand you correctly, then:
Dim myPdf As String =
IO.Path.Combine(IO.Directory.GetParent(Application.ExecutablePath).FullName, "myPdfFile.pdf")
Another way you could do it is by using something like the code below;
Private Sub FamilyLocateFile_Click(sender As Object, e As EventArgs) Handles FamilyLocateFile.Click
If LocateFamilyDialog.ShowDialog = DialogResult.OK Then
FamilyWMP.URL = LocateFamilyDialog.FileName
ElseIf LocateFamilyDialog.ShowDialog = DialogResult.Cancel Then
MsgBox(MsgBoxStyle.Critical, "Error!")
End If
End Sub
What this will do is play a file in a Windows Media Player ActiveX object. The file can be selected with an OpenFile Dialog, which in this case is called LocateFamilyDialog. You don't need the ElseIf part of the statement, but you will need to insert an open file dialog and a control that can display PDFs. I think it'll work with WebBrowsers, but I'm not sure.

Print to XPS without a Save As dialog

How can I save an xps file by printing to a virtual printer without using the Save File As dialog? When I call the print method, a dialog automatically pops up asking the user to specify the file name and path. This only works when creating brand new files; it throws an error 'you do not have permission to write to that file...' if I attempt to overwrite an existing file. Anyways, I want the user to be able to specify the file name in my own dialog, not the one that is autamatically called by the printDocument's Print method.
Public Event PrintPage As System.Drawing.Printing.PrintPageEventHandler
Private WithEvents Doc As New Printing.PrintDocument
Public Sub SaveXPSFile()
Doc.PrinterSettings.PrinterName = "Microsoft XPS Document Writer"
Doc.PrinterSettings.PrintFileName = "C:\Users\POConnell\Documents\t.xps"
Doc.Print()
Doc.Dispose()
End Sub
Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles Doc.PrintPage
'drawing commands go here
End sub
It's a couple of months late, but here we go.
2 questions, two answers.
Question 1:
How can I save an xps file by printing to a virtual printer without using the Save File As dialog?
Answer 1: You were close. I think you're looking for
Doc.DefaultPageSettings.PrinterSettings.PrintToFile = True
Doc.DefaultPageSettings.PrinterSettings.PrintFileName = "C:\Users\POConnell\Documents\t.xps"
Here is my implementation:
(Legal paper size, landscape mode)
Using prn As New PrintDocument
With prn
.PrinterSettings.PrinterName = "Microsoft XPS Document Writer"
AddHandler .PrintPage, _
AddressOf Me.PrintPageHandler
.DefaultPageSettings.Landscape = landscape
.DefaultPageSettings.PaperSize = New PaperSize("Legal", 850, 1400)
If My.Computer.FileSystem.FileExists("C:\temp\Log.oxps") Then My.Computer.FileSystem.DeleteFile("C:\temp\Log.oxps")
.DefaultPageSettings.PrinterSettings.PrintToFile = True
.DefaultPageSettings.PrinterSettings.PrintFileName = "C:\temp\Log.oxps"
.Print()
RemoveHandler .PrintPage, _
AddressOf Me.PrintPageHandler
End With
End Using
As you can see, I use the oxps file format, but it should still work just the same for you.
Question 2: it throws an error 'you do not have permission to write to that file...' if I attempt to overwrite an existing file.
Answer 2: Check if the file already exists prior to printing the file, and delete it if it does. Of course it will fail attempting to create a file that already exists.
For some reason using My.Computer.FileSystem.DeleteFile is faster than the traditional Kill() and System.IO.File.Delete, which both require the thread to sleep for ~1-200ms prior to recreating the file, or else a different access denied error will occur.
Hopefully this helps someone in the future!

How to close parent form and open child?

Hey guys before I was just hiding the parent form, but now when I try to read from the parent file it says it can't because it's already running in a process. I followed some tutorial and it said to go to the project properties and have the application stop running when all the forms are closed.
But now since I did that it says the directory can't be found probably because I am reading the input from the parent form. Anyways here is my code
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" + frmLogin.txtUser.Text))
How should I go about doing this?
Edit:
Private Sub btnHunter_Click(sender As System.Object, e As System.EventArgs) Handles btnHunter.Click
selection = "Hunter"
writeData.classSelection()
End Sub
This is what I have when the button is clicked.
Here is the classSelection sub:
Public Sub classSelection()
If frmClass.selection = "Hunter" Then
writeFile1.WriteLine(frmClass.selection)
End If
If frmClass.selection = "Gatherer" Then
writeFile1.WriteLine(frmClass.selection)
End If
If frmClass.selection = "Farmer" Then
writeFile1.WriteLine(frmClass.selection)
End If
writeFile1.Close()
End Sub
The error points to this line:
If frmClass.selection = "Hunter" Then
Saying part of the file path cannot be found.
If you want to read input textbox in closed parent form, you have to declare public var
Make a new module in your project .. and add this
public sLogin as String
And before you hide or close frmLogin .. add this
sLogin = txtUser.Text
So, you could change your code with
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" & sLogin))
matzone has given you a good hint. And to check exactly what your path is, just add a MessageBox using variables :
Dim writePath1 As String
Dim writeFile1 As StreamWriter
writePath1 = "C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" & sLogin
If MessageBox.Show(writePath1, "Continue ?", MessageBoxButtons.YesNo) = DialogResult.Yes Then
writeFile1 = New StreamWriter(File.OpenWrite(writePath1))
' ...
writeFile1.Close() ' Very important ! Adrian pointed it out.
End If
^^ and if it works, you can discard the Dialog test or replace it by some test code like If File.Exists(...)
However, I don't understand wether you want to close the parent Form or hide it. It's different !
Closing the parent Form will discard any access to parent Form members, including txtUser.Text.
If you want to close the parent Form, the ChildForm should not be a child of that parent you are trying to close, or you must just hide the parent Form :
frmLogin.Hide() ' Not frmLogin.Close()
If you close frmLogin, frmLogin.txtUser won't be accessible, or use sLogin provided by matzone instead. Alternatively, you should pass frmLogin.txtUser.Text value to a custom property of ChildForm.
Imports System.IO
Public Partial Class ChildForm1
' Inherits System.Windows.Form
' ...
Private _txtUserFile As String
Public WriteOnly Property TxtUserFile() As String
Set(ByVal NewFileName As String)
_txtUserFile = NewFileName
End Set
End Property
Public Sub LoadFile()
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" & txtUserFile))
' ...
writeFile1.Close()
End sub
' ...
End Class
Then use this in parent Form :
MyChildForm.TxtUserFile = Me.txtUser.Text
' Me.Close() ' This will definately KILL Form1 (the parent one)
Me.Hide() ' Always use Hide() until you'll terminate your Application
MyChildForm.Show()
MyChildForm.LoadFile()
^^ but this is not a good code either ! Your problem remains unclear (at least for me)
"Still saying it can't find part of the path", then check the path..
Does the file actually exists ?
Does the path contains glitch ? (use the provided MessageBox test)
Does your account can access that directory ? (Windows configuration and account levels)
Well !
In fact, the problem could be somewhere else.
For example, I was able to reproduce your exception by providing an empty string [""] as the value of, either :
frmLogin.txtUser.Text ' = ""
' or
sLogin ' = ""
' or
txtUserFile ' = ""
In fact, I get the "Could not find a part of the path..." exception because the StreamWriter couldn'd read/write to a File, as I didn't provided a valid FileName for that file. As the filename parameter was an empty string "", the provided path for StreamWriter was just representing a directory instead of a file and an exception was raised.
Now, you should check wether you have a valid path before building a new instance of StreamWriter to get sure you are actually pointing to a File ?
Dim writeFile1 As StreamWriter
Dim MyEntirePath As String = "C:\Users\...\Accounts\" + frmLogin.txtUser.Text
MessageBox.Show(MyEntirePath) ' would be enough to be sure your path is correct
' Some test code here...
If everythingOK then ' create the StreamWriter...
writeFile1 = New StreamWriter(MyEntirePath)
' ...
' ...
Also, it's not a good idea to create your streamwriter, and use it in another part/method of your code. You never known if one day, you'll change your code, and forget to make the link between
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" + frmLogin.txtUser.Text))
' plus
Private Sub btnHunter_Click(sender As System.Object, e As System.EventArgs)
...
End Sub
' plus
Public Sub classSelection()
...
writeFile1.Close()
End Sub
^^ too much "here and there"...
You'll obviously also get an exception if you try to click btnHunter twice.. I don't know what is the purpose of your code nor how it works, it looks like a game.. But I would use File.Exist(..) checks, create the file before, if none, and put that in a Try/Catch to check if I eventually don't have administrator rights to write to that directory. Otherwise, make a code that allow user to read/write files to a custom folder. Andalso, you have :
Application.StartupPath
^^ Very usefull, like :
Dim MyFilePath As String = Application.StartupPath + "\Datas\MyText.txt"
After two weeks of coding, I usually forget where I put those "C:\blabla.." or "D:\gnagna\" or what classes actually uses those absolute reference paths. I've dropped this way of getting directories long ago since the day I moved to Win7 on another computer and all such applications I developped using that approach was doomed...