c# Fill a richTextBox with Microsoft Word or Wordpad - c#

I have a question.
I have a winform with a richTextBox1, this textbox is readonly, but there is a "Edit"-Button. When you press the Edit-Button, Wordpad or maybe Microsoft Office will open, then you write a Text in the Office tool and after you close word/wordpad, the richTextBox1 will be filled with the Text from the Wordpad.
Is this possible? and if Yes, how ?

It is very simple:
private void btnEdit_Click(object sender, EventArgs e)
{
var myFileName = #"myRtb.rtf";
//Save your RichTextBox text to a file.
richTextBox1.SaveFile(myFileName);
string PathToApp = #"Microsoft Office Word 2007.lnk";
//Make a System.Diagnostics.Process object
Process runProg = new Process();
try
{
//With path to your MS Office application
runProg.StartInfo.FileName = PathToApp;
//Command line arguments to open file
runProg.StartInfo.Arguments = "/t" +" "+ myFileName;
runProg.StartInfo.CreateNoWindow = true;
//And start your application and also open file
runProg.Start();
}
catch (Exception ex)
{
}
}
A documentation to Microsoft Office products command line arguments:
https://support.office.com/en-us/article/Command-line-switches-for-Microsoft-Office-products-079164CD-4EF5-4178-B235-441737DEB3A6

I might have an answer.
Start up Word with a parameter for the desired file location. Then edit your file and save it. When your app detects that Word has closed or the file has been created, whichever, then you can load that word file into your textbox.
It's a little more long winded than that I'm sure, but that's the gist, totally possible.
I'd begin by looking into Aspose, a library for Microsoft products that exposes simple APIs to use.
Good luck!

Related

Is it possible to save a word document by bypassing the Save or SaveAs methods c#

I have a MS Word AddIn that launches a winform which allows the user to specify some additional metadata which is then saved as an xml file along with a copy of the document in a specified location.
This all works fine when run from a standalone Word document, however one of the areas this will be used is where a Word document is launched inside an application (EMIS WEB). It launches a copy of Word from the local machine which is fine as it allows the AddIn to be run.
When I try to save the document I get a Command Failed. error. The XML file saves no problem: xml.Save(path + docName + ".xml");.
The application prompts with it's own 'save' like dialog.
At first I thought it was the application removing focus from the document therefore this.Application.ActiveDocument.SaveAs failing because it wasn't the Active Document. So I tried getting the Document object when it was active and passing it through to the saveDoc method so that I could set it as the Active Document like so:
public void saveDoc(string doc, Word.Document wd)
{
string path = #"\\servername\folder\subfolder\";
object filename = path + doc + ".docx";
try
{
wd.Activate();
this.Application.ActiveDocument.SaveAs(ref filename);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
However this made no difference, the application's dialog still pops up, and regardless of whether I click OK or Cancel to the dialog it does not process the SaveAs command.
I have come to the conclusion that the application is intercepting the Save/SaveAs command and doing its own thing instead.
So is it possible to save a word document by bypassing the Save or SaveAs methods? Is there a way round this?
Figured it out, fortunately there was not a strict requirement to save it as a .doc or .docx so I have opted for .pdf. I have got round the application intercepting the Save commands by using the Document.ExportAsFixedFormat Method with wdExportFormatPDF to save it as a PDF.
So the final code looks like this, and it works a treat:
public void saveDoc(string doc)
{
string path = #"\\servername\folder\sub-folder\";
string filename = path + doc + ".pdf";
try
{
this.Application.ActiveDocument.ExportAsFixedFormat(filename, WdExportFormat.wdExportFormatPDF);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

C# OpenFileDialog: The filename, directory name, or volume label syntax is incorrect

I need to programmatically open a document from Sharepoint in Visio. But when I navigate to the network folder, select a document and click on open, I
get the following error:
The filename, directory name, or volume label syntax is incorrect
When searching for the error, I found the following documentation: https://msdn.microsoft.com/en-us/library/ms832054.aspx. So I guess that the file name contains illegal characters. I tried to use the FileOk event to overwrite the validation of the fileName:
public void openFile() {
OpenFileDialog sf = new OpenFileDialog();
sf.FileOk += openFileDialog_FileOk;
if (sf.ShowDialog() == DialogResult.OK)
{
var app =(Microsoft.Office.Interop.Visio.Application)context.Application;
app.Documents.Open(sf.FileName);
}
}
private void openFileDialog_FileOk(object sender, CancelEventArgs e)
{
var sfd = sender as OpenFileDialog;
var file = new FileInfo(sfd.FileName);
if (file.Name.Contains('#'))
e.Cancel = true;
}
but the event does not fire. Using the standard Visio interface it is possible to open files from Sharepoint but the file dialog looks a bit different:
How can I get a similar file dialog? And so my questions is: how can I programmatically open a Visio document from Sharepoint (network folder)?
Since Visio does not provide app.GetOpenFilename API, you are out of luck. But you could use another office application for the same. Like Excel for example:
var excel = new Excel.Application();
var fileName = excel.GetOpenFilename();
excel.Quit();
var visio = new Visio.Application();
visio.Documents.Open(fileName);
which provides a "similar dialog" and "normal url", that is understood by Visio API without any issues.
The problem probably is that Visio API does not understand UNC DAV file path format with #SSL part, that is provided by the default "built-in" OpenFileDialog (or may be something else as well). Check what is the value of the .FileName returned by the default dialog. BTW, to prevent error messages, it's enough to set sf.CheckFileExists = false, maybe that will be enough.

Opening an Excel file in C# using Process.Start

I'm trying to open an excel file using a button click. And for some reason it's not working. I've tried several things. Any ideas why they are not working?
Method 1 I have tried. This opens the file manager but does not open the proper file. It is definitely using the proper path to the file and the file does exist
private string fileCopy;
public RepairResultsControl()
{
InitializeComponent();
}
public void Show(PSRepair.AnalysisResults analysis, string pathNameCopy)
{
fileCopy = pathNameCopy;
Show();
}
private void btnGoToFile_Click(object sender, EventArgs e)
{
Process.Start("explorer.exe", "/select,"+ fileCopy);
}
Method 2. This just didn't open anything not sure why
System.Diagnostics.Process.Start(#"C:\Users\username\Documents\newTest.xlsx");
Normally, Process.Start(#"C:\Users\username\Documents\newTest.xlsx"); would open your document in Excel.
However, you say in a comment that you are doing this from an Excel add-in which runs in the background. The solution needs to take this into account (the code sample assumes that you have a VSTO add-in, otherwise you need to adjust accordingly):
// make the running Excel instance visible
Globals.ThisAddIn.Application.Visible = true;
// open the workbook using Excel interop
Globals.ThisAddIn.Application.Workbooks.Open(fileName);
Try running as an admin
Check for exceptions, also the start method should return a bool, check to make sure it is true.
Make SURE your xlsx files are associated with Excel(easy check for this is at a command prompt, type in your filename and hit enter... if excel opens you are good)
Check your system error logs.

Opening MS Word File

I am using document.Active() method which is a part of Microsoft.office.interop.word namespace. I want to open the file i.e. I want to see the file opened in the Word application. I have set thetrackRevisions property true and rest of all the things.
I just want the file to open NOT IN SAVE-AS MODE. Just open so that when I open up a document from DB or from my PC drives I just want it to open.
Here is the code that I am executing:
Word.Document tempDoc = app.Documents.Open("E:\\xyz.docx");
// Activate the document so it shows up in front
tempDoc.Activate();
tempDoc.TrackRevisions = true;
foreach (Revision rev in tempDoc.Revisions)
{
string editedBy = rev.Author;
//string what = rev.Cells;
}
tempDoc.Close(ref Nothing, ref format, ref Nothing);
Any suggestions that come to your mind?
You just want word to open?
Have you tried
Process.Start('path to word plus filename');

C# After I save a .csv in Excel, how do I open it?

I did a little research, and an unsure if I should be using
the Microsoft.Office.Interop.Excel
Just to clarify with the example: I'm taking a .txt, and doing stuff, then saving it as a .CSV (Comma Separated Values). I want to then open it (on button click or something...)
How can this be done?
Pair to your comment:
I want it to open in Excel.exe. It should be a separate window that launches after my program is done with its conversion
Simply start it using System.Diagnostics.Process class:
using System.Diagnostics.Process;//at top of your application
//
//At button click or after you finish editing
//
Process excel = new Process();
//if the excel was installed in the target machine and the default program to open csvs
//then you can simply just call process start and put the file path, like:
excel.Start(#"Your edited csv file path");
//otherwise:
excel.StartInfo.FileName = #"The excel application file path";
excel.StartInfo.Arguments = #"Your edited csv file path";
excel.Start();
You can start the excel process with the file path as command line parameter (excel.exe C:\myFile.csv). This will open it in excel.
Yup, Microsoft.Office.Interop.Excel is what you will need to open the CSV file in Excel.
Depends on which framework you are using (i.e. Silverlight or Windows Forms).
If I were you I'd be using OpenFileDialog to read the values from the comma seperated list into a string or a class. The sample below is for silverlight.
private void bOpenFileDialog_Click(object sender, RoutedEventArgs e)
{
// Create an instance of the open file dialog box.
var openFileDialog1 = new OpenFileDialog();
// Set filter options and filter index.
openFileDialog1.Filter = "CSV File (.csv)|*.csv|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false;
// Call the ShowDialog method to show the dialog box.
bool? userClickedOK = openFileDialog1.ShowDialog();
// Process input if the user clicked OK.
if (userClickedOK == true)
{
// Open the selected file to read.
System.IO.Stream fileStream = openFileDialog1.File.OpenRead();
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
{
// Read the first line from the file and write it the textbox.
tbResults.Text = reader.ReadLine();
//the results of your CSV are now stored in tbResults.Text
//optionally you could parse the .CSV using string.Spit(',') into a string array
}
fileStream.Close();
}
}
Is this a WinForms, WPF, or ASP.NET application? If you use the Office Interop libraries you are dependent on Office being installed on that machine. If it's a web server, you don't want to run Excel that way.
Check out www.SpreadSheetGear.com. No affiliation, just very satisfied.

Categories

Resources