Unhandled exception in Adobe Reader while passing a search parameter in C# - c#

I'm writing a WinForms application and there's a method to search text strings into an array of pdf files. When the given text is found, the method should open the proper file, highlighting said text.
I followed the specifics found in the Parameters for Opening PDF Files document, and this is the part of the code where I call the reader:
string arg = "/A search=\"" + parametri.testoDaRicercare + "\" \"" + file + "\"";
Process.Start("AcroRd32.exe", arg);
where parametri.testoDaRicercare is the string with the given text and file is the path to the pdf file.
Now, it works flawlessly with Adobe Reader XI, while I am given this error using Adobe Reader DC:
Unhandled exception in 0x61D6796F (AcroRd32.exe) in AcroRd32.exe:
0xC0000005: access violation while reading the path 0x000002C0. An Exception occurred.
By the way I don't know whether it's a simple Adobe+Win10 issue or whatever, because if I set the parameters to open the pdf at a certain page it works fine on both machines.
string arg = "/A \"page=" + pagina + "\" \"" + file + "\"";
Process.Start("AcroRd32.exe", arg);

Related

Unable to write AppedText in file

I need create a file and need to write the every exception in a file. i am using bellow code to do that.
File.Create(filePath);
File.AppendText("Exception Detail Start-------------------------------------------");
File.AppendText("Stack Trace :" + ex.StackTrace );
File.AppendText("Error :" + ex.Message );
File.AppendText("Exception Detail End-------------------------------------------");
But I'm getting the below error:
Additional information: Access to the path 'C:\Program Files (x86)\IIS Express\Exception Detail Start-------------------------------------------' is denied`
File.AppendText takes a file path and returns a StreamWriter. So in your case you are passing the exception message as the file path, and hence the file is not found (it is looking file a file in the current directory named "Exception Detail Start-------------------------------------------").
In your case you might want to use File.AppendAllText.
Opens a file, appends the specified string to the file, and then
closes the file. If the file does not exist, this method creates a
file, writes the specified string to the file, then closes the file.
Or File.AppendAllLines.
Appends lines to a file, and then closes the file. If the specified
file does not exist, this method creates a file, writes the specified
lines to the file, and then closes the file.
Example:
File.AppendAllLines(filePath, new string[] {
"Exception Detail Start-------------------------------------------",
"Stack Trace :" + ex.StackTrace,
"Error :" + ex.Message,
"Exception Detail End-------------------------------------------"
});
You don't write to the file you created.
FileStream writer = File.Create(filePath);
writer.AppendText("Exception Detail Start-------------------------------------------");
writer.AppendText("Stack Trace :" + ex.StackTrace );
writer.AppendText("Error :" + ex.Message );
writer.AppendText("Exception Detail End-------------------------------------------");
This should work.
Your C\program files (x86) path usually requires administrative right to write files. Try starting your application as administrator. (Alternatively start visual studio as administrator and run your project)
If it successfully writes to the file when run as administrator maybe consider choosing a folder that requires no administrative priviledges or add priviledges to a chosen folder for your program.

How to read and write csv file when it is opened with Excel by the user in parallel with C#?

This is the first question I asked on stackoverflow, very exciting. So sorry about my grammar and other type mistakes, I would appreciate if you correct them. I want to write a program that reads a csv file if it exists in the specific folder first, stores it in List variable, add some new lines and writes it to the same file. This process will be repeated continuously in a while block.
While the file is being read and written by the program, if it is opened with Notepad, it doesn't give an error and the program could access the file in parallel. But if it is opened with Office Excel, program gives error that says "file access is denied because it is used by another process..". I want to ask you that:
1) Is it possible to give priority to the program, so program can still access the file but user cannot? Or is it possible both program and user can access the file?
2) If the solution is opening the file with Notepad, is there a way to set default program for this file as Notepad? Or how can I change default program for csv files as Notepad from C#?
Reading and writing parts of the code is as bellows:
List<string> csvLines = new List<string>();
string address = folderpath + #"\PLC_LOGLARI";
if (!Directory.Exists(address))
Directory.CreateDirectory(address);
string fileAddress = address + #"\" + fileName + "_" + machineNo + "_1.csv";
if (Directory.EnumerateFiles(address).Any(f => f.Contains(fileName + "_" + machineNo)))
{
string[] addressArray = Directory.GetFiles(address, fileName + "_" + machineNo + "*.*");
FileInfo fileInformation = new FileInfo(addressArray[addressArray.Length - 1]);
long fileSize = fileInformation.Length;
if (fileSize > 5000000)
{
int fileNo = int.Parse(addressArray[addressArray.Length - 1].Substring(addressArray[addressArray.Length - 1].LastIndexOf('_') + 1, 1)) + 1;
fileAddress = addressArray[addressArray.Length - 1].Substring(0, addressArray[addressArray.Length - 1].LastIndexOf('_') + 1) + fileNo.ToString() + ".csv";
}
else
{
fileAddress = addressArray[addressArray.Length - 1];
csvLines = File.ReadAllLines(address).ToList();
}
}
else
{
string[] headings = makeHeadings();
csvLines.Add(headings[0]);
csvLines.Add(headings[1]);
}
string newLine = "";
// some operations and calculations for newLine
// some operations and calculations for newLine
// some operations and calculations for newLine
newLine = newLine.Substring(1, newLine.Length-1);
csvLines.Add(newLine);
File.WriteAllLines(fileAddress, csvLines.ToArray());
Thanks for your help.
For question 2: In order to change the default program, if you are using Windows, you could click start and find/type 'Default Programs'. Depending on the version of windows, basically find 'Associate a file type of protocol with a program' or 'choose a default application by file type' and adjust the csv file to use a new default program.
I would be very careful if both program and notepad are able accessing the file in the same time. The reason why it was blocked in the first place was to prevent overridding the content of the file, thus probably test it first if you open it in the program and notepad. Then the program make some update - and you also make a different update with the notepad. Would both changes be recorded? As I suspect the 'last save' win in which you may lost some of your changes.
For question 1: I was guessing that whoever open the file first got the lock of that file. As such, if Excel was opening the file - then the program would have that error. Vice versa, if the program had opened the file - then the Excel may have problem opening that file. I'm not sure how to give priority to the program.

How to convert from PDF to XPS?

I use the following method to print a XPS file with adobe acrobat:
private void GenerateXPS(String filename)
{
Process proc = new Process();
proc.StartInfo.FileName = "AcroRd32.exe";
proc.StartInfo.Arguments = "/t " + filename + ".pdf" + " " + "\"Microsoft XPS Document Writer\"";
proc.Start();
}
But the problem is, the Microsoft XPS Document writer needs a filename where to store the document. Now I'm asked to enter this filename by Adobe Acrobat, but I want to pass this filename as well in the arguments. Or if this is not possible just use the same filename. Is this possible?
If it isn't mandatory that you use acrobat, you might try printing the file directly to the Microsoft XPS Document writer. You can do this without the UI popping up. (see Feng Yuan's blog post for more details)

System.IO.File.ReadAllText(path) does not read the html file

I want to read the html file.And for that I use System.IO.File.ReadAllText(path).It can read all the html file but there is one file which is not read through this function.
I have also used
using (StreamReader reader = File.OpenText(fileName)) {
text = reader.ReadToEnd(); But still there is same problem.
What is the reason can be there ? And for that what can be the solution ? Or any other way to read the file ?
I'll take a wild guess:
The file contains unicode sequences for extended chars and the diagnose is based on (mismatched) length.
if I debug the code in the it looks
like
"<\0h\0t\0m\0l\0>\0<\0h\0e\0a\0d\0>\0\r\0\n\0<\0M\0E\0T\0A\0
\0h\0t\0t\0p\0-\0e\0q\0u\0i\0v\0=\0\"\0C\0o\0n\0t\0e\0n
Which is a valid beginning of a HTML file except for the very first char. The file is probably damaged by missing a unicode marker at the start. This damage was probably caused when it was written and is not (easy) repairable now.
You could try setting the WebClient.Encoding to UTF8 (and try a few ASCII as well).
Does MsgBox shows anything? Any error? What does varText.Length show?
string varText = File.ReadAllText(varFile, Encoding.Default);
MessageBox.Show(varFile + " Text: " + varText + " Lenght: " + varText.Length);
Verify in MessageBox that the path to file is correct, verify that the access rights from inside your application are the same as if you would be reading the file with notepad.
Came across this on google recently. The correct way to do it is via WebClient...
WebClient client = new WebClient();
String guestMsg = client.DownloadString("C:\\temp\\TheBarGuestDetailsEmail.htm");
File.ReadAllText will mess up the html when it's doing a read, and characters like £ or ' will get messed up.

Open a pdf file programmatically at a named destination

I would like to open a PDF file at named destination using WinForms (C#). Here is my code:
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
myProcess.StartInfo.FileName = "Acrobat.exe";
myProcess.StartInfo.Arguments = "/A \"nameddest=Test2=OpenActions\" C:\\example.pdf";
myProcess.Start();
It always opens the file at page 1 even having the destination Test2 at page # 10. It basically ignores the destination parameter. However if I use another parameter like the page number it works fine. For example:
myProcess.StartInfo.Arguments = "/A \"page=5=OpenActions\" C:\\example.pdf";
will always open the PDF document at page 5.
Thanks in advance for your help
I use the following code:
string strNamedDestination = "MyNamedDestination"; // Must be defined in PDF file.
string strFilePath = "MyFilePath.pdf";
string strParams = " /n /A \"pagemode=bookmarks&nameddest=" + strNamedDestination + "\" \"" + strFilePath + "\"";
Process.Start("AcroRd32.exe", strParams);
Note the "/n" inside the params. It makes Adobe to always open a new document. Otherwise, if the document was already opened, it doesn't move it to the right Named Destination. It depends on the behaviour you want for your application.
Regarding the Adobe documentation when opening a PDF document from a command shell, you can pass the parameters to the open command using the /A switch using the following syntax:
myProcess.StartInfo.Arguments = "/A \"nameddest=Test2=OpenActions\" C:\\example.pdf";
If I omit the OpenActions parameter everything works fine like:
myProcess.StartInfo.Arguments = "/A \"nameddest=Test2\" C:\\example.pdf";
I'm not sure why the OpenActions breaks opening the file but with omitting it works fine.
I have a csv with 5 columns.
Column1 contains PDF names and Column5 pagenumbers.
The executable displays the csv.
When I doubleclick on a line in the csv the following code is executed :
ListViewItem item = lvwItems.SelectedItems[0];
Process myProcess = new Process();
myProcess.StartInfo.FileName = "Acrobat.exe";
myProcess.StartInfo.Arguments = "/A page=" + item.SubItems[4].Text + " " + item.Text;
myProcess.Start();
This opens the selected PDF which name is in item.Text on the page which pagenumber is in item.SubItems[4].Text
Have you set up the destinations? You need to be have the standard or professional versions of Adobe Acrobat in order to do this:
http://kb2.adobe.com/cps/317/317300.html
Adobe Reader has a few bugs regarding opening to named destinations. Take a look at http://xenon.arcticus.com/open-pdf-named-destination-dde-c-c for some information and workarounds.

Categories