C# WPF Open File and edit certain text - c#

So let's say I have a program with just a text box and an okay button. The user types in whatever word he wants, and when he clicks ok, it opens a specific file called Test.doc and CTRL+F for the word "test" and replaces it with whatever the user entered into the text box. How can I open said file and replace instances of the word test with the user's defined word?

Ignoring the format of the document, you could literally use the folowing for any type of file:
var contents = System.IO.File.ReadAllText(#"C:\myDoc.doc");
contents = contents.Replace("Test", "Tested");
System.IO.File.WriteAllText(#"C:\myDoc.doc", contents);
The best way would be to use the ms office interop library though.
Andrew

A number of things:
I'd recommend using a FileDialog to get the file's location. This lets you select the file to edit, but also gives you functionality to only show the file types that you want to handle in this program.
If you're handling .doc's, I'd suggest you look into VSTO and opening word docs. Here's a guide I found after a quick search. I'd suggest using it as a place to start, but you'll need to look around for more specifics.
Lastly, the string.Replace("", ""); method is probably very helpful in the CTRL-F functionality. You should be able to extract a string of the text from whatever document you're analyzing and use that method.

Related

Is there any way to automatically add many properties on VS2019?

Don't judge me, but I have an object with over 100 properties, most of them string.
Is there anyway to automatically add them to the code, without extensive typing?
I have them all in a text file with correct casing. I looked for plug ins, but couldn't find any (maybe using wrong keywords?)
I am assuming your file looks like:
Property
SomeOtherProperty
Test
The easiest way would be to use a CSV -> C# Model generator
Steps
Change it to be comma separated, you can do this with C#:
var path = #"C:\Path\To\Your\File.txt";
var text = File.ReadAllText(path);
text = text.Replace(Environment.NewLine, ",");
File.WriteAllText(path, text);
Open the file and copy its contents to your clipboard.
Now open the C# Class from CSV tool.
Paste the contents and voila you have a C# model!
Notepad++ can do it quite easily.
Open your text file with notepad++ and press Ctrl+H
Fill in the fields like below:
search for (.*)
replace with public string \1 {get;set;}
tick "regular expression"
press "Replace all"
And voilĂ :
Note that this should work with any editor that handle regex (as stated by #Klamsi in the comments section)

Word - Replace text by hyperlinks

I am working on a MS-Word addin that reads the content of a document and replaces every occurence of a specific word by a hyperlink.
So far, I came up with this working algorithm.
// Initializes the Find parameters
searchRange.Find.ClearFormatting();
searchRange.Find.Forward = true;
searchRange.Find.Text = "foo";
do
{
searchRange.Find.Execute(Wrap: Word.WdFindWrap.wdFindStop);
if (searchRange.Find.Found)
{
// Creates a Hyperlink at the found location in the current document
this.WordDocument.Hyperlinks.Add(searchRange, externalLink, link, "bar");
}
searchRange.Find.Execute(Wrap: Word.WdFindWrap.wdFindStop);
} while (searchRange.Find.Found);
This code works, however, it can be slow on bigger documents. Thus, instead of adding hyperlinks one by one, I wanted to simply to use the Find.Replacement object and with the WdReplace.ReplaceAllproperty.
However, I cannot manage to replace my search result by a Hyperlink.
Is there a way to replace a piece of text by a hyperlink using the Replacemethod ?
In other words, I'd like to find a way to do this :
Find.Replacement.Text = new Hyperlink(...);
On an other side, I've seen that, by hitting Alt + F9in Word, we can see hyperlinks as code.
The code looks like this :
{ HYPERLINK \l "link" \o "Caption" }
Another solution would be to be able to set the text replacement as that string and make Word interpret it and thus, create the link.
Thanks for reading.
As far as I know, fields can only be inserted programmatically, or by using CTRL-F9. There are two possible reasons for this that I see:
They are not simple text. They have two ranges, the Code and the Result, only one of which is displayed at any time.
How else would a user insert text that looks like a code but is not supposed to be one, unless there was a special mechanism to create one?

C# replace certain string when typing in any application

I want to make an application that will replace a certain string when I type in any textfield of any application (online textboxes, notepad, word, email, etc..)
For example if I'm writing in notepad++ and I type [for] and press space or enter I want my C# application to work in background, access the field and replace that string with a predefined string in my C# code.
The result would for example be:
for($i = 0; $i < X; $i++)
{
// ....
}
For example if I'm writing a word document and I input [FIRSTPAGE] I would want that to be replaced with a random string I setup early.
Later on I will setup an app that will let me change these on the fly.
I tried searching google but I found no information on anything similar.
I just need to find a way to replace a string in any textfield.
Hope this makes sense. Thanks for your help.
Create a global keyboard hook, C# : Keyboard Hook shows how you can do it.
Once hook is created monitor handle the keylog for typed word. Once the typed word is found use SendKeys to send keystrokes virtually.
There's a really cool library called Scintilla.NET - http://scintillanet.codeplex.com/
It's usually used for building your own code editor with syntax highlighting support.
But it has the auto-suggest feature you are after, i.e:

How to SaveAs in Word 97 using Word version 12 component?

I'm using the Word 2007-component in C#.
I want to save the Word document as a Word97(-2003)-document, because not everyone uses Word 2007/2010.
I thought it is easy by using the following command
document.SaveAs(AFullFileName, WdSaveFormat.wdFormatDocument97);
But then the SaveAs-dialog is shown with the assumption that I want to save it as a docx-file.
I've noticed that the WdSaveFormat.wdFormatDocument-flag has had the same value as WdSaveFormat.wdFormatDocument97-flag.
So I think I have to do more then only using those parameters in the SaveAs-command.
Can anybody help me? I would like the format to be correct and not to see the Save As dialog.
Thanks.
As already suggested in comments most probably you must check that save file name, (i.e. AFullFileName argument) extension is properly set to .doc, not .docx. Word enforces that for security reasons.
I've solve this by saving the document under another filename.
I tried to save the file as doc-file by using Word 2007. But it seems that the file can't be overwritten. I tried to change the type of Save As. I chose several times Word97-doc. But nothing was saved. And everytime the type turns back as a docx-document.
And finally when I change the filename, the document saved as a Word97-document.

How to replace text in a PDF with C#?

I saw a lot of solutions in here but none are clear or good answers.
Here is my simple question, hoping with a straight answer.
I have a PDF file (a template) which is created having text something like this:
{FIRSTNAME} {LASTNAME} {ADDRESS} {PHONENUMBER}
is it possible to have C# code that replace these templates with a text of my choice?
No fields, no other complex stuff.
Is there any Open source library helping me achieve that?
This thread is dead, however I'm posting my solution for other lost souls that might face this problem in the future. Unfortunately my company doesn't allow posting code online so I'll describe the solution :).
So basically what you have to do is use PdfSharp and modify this sample to replace text in stream, but you must take into account that text may be split into many parentheses (convert stream to string to see what the format is).
Then, with code similar to this sample traverse through source pdf page by page and modify current page by searching for PdfContent items inside PdfReference items and replacing text in content's stream.
The 'problem' with PDF documents is that they are inherently not suitable for editing. Especially ones without fields. The best thing is to step back and look at your process and see if there is a way to replace the text before the PDF was generated. Obviously, you may not always have this freedom.
If you will be able to replace text, then you should be aware that there will be no automatic reflow of the text following the replaced text. Given that you are fine with that, then there are very few solutions that allows you to replace text.
I know that you are looking for an OpenSource solution so I feel reluctant to offer you a commercial solution. We offer one called PDFKit.NET. It allows you to extract all content on a page as so-called shapes (text, images, curves, etc.). See method Page.CreateShapes in the type reference. You can then programmatically navigate and edit this structure of shapes and then write it back to a PDF again.
Here it is:
http://www.tallcomponents.com/pdfkit
Disclosure: I am the founder of TallComponents, vendor of this component
For simple text replace use iTextSharp library.
The code that replace one string with another is below.
Note that this will replace only simple text and may not work in all cases.
//using iTextSharp.text.pdf;
void VerySimpleReplaceText(string OrigFile, string ResultFile, string origText, string replaceText)
{
using (PdfReader reader = new PdfReader(OrigFile))
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
byte[] contentBytes = reader.GetPageContent(i);
string contentString = PdfEncodings.ConvertToString(contentBytes, PdfObject.TEXT_PDFDOCENCODING);
contentString = contentString.Replace(origText, replaceText);
reader.SetPageContent(i, PdfEncodings.ConvertToBytes(contentString, PdfObject.TEXT_PDFDOCENCODING));
}
new PdfStamper(reader, new FileStream(ResultFile, FileMode.Create, FileAccess.Write)).Close();
}
}
As stated in similar thread this is not really possible an easy way. The easier way it seems to be getting a DocX file and using DocX library which allow easy word swapping and then converting your DocX to PDF (using PDF Creator printer or so).
Or use pdf sharp/migradoc to create new documents.
Updating in PDF is hard and dirty. So may be adding a content on top of existing will work for you as well, as it worked for me. If so, here's my primitive, but working solution covering a lot of cases ("covering", indeed):
https://github.com/astef/PatchPdfText

Categories

Resources