How to open a PDF file that is also a project resource? - c#

I have a PDF file that I have imported in as a resource into my project. The file is a help document so I want to be able to include it with every deployment. I want to be able to open this file at the click of a button.
I have set the build action to "Embedd Resource". So now I want to be able to open it. However, When I try accessing the resource - My.Resources.HelpFile - it is a byte array. How would I go about opening this if I know that the end-user has a program suitable to opening PDF documents?
If I missed a previous question please point me to the right direction. I have found several questions about opening a PDF within an application, but I don't care if Adobe Reader opens seperately.

Check this out easy to open pdf file from resource.
private void btnHelp_Click(object sender, EventArgs e)
{
String openPDFFile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\HelpDoc.pdf";//PDF DOc name
System.IO.File.WriteAllBytes(openPDFFile, global::ProjectName.Properties.Resources.resourcePdfFileName);//the resource automatically creates
System.Diagnostics.Process.Start(openPDFFile);
}

Create a new Process:
string path = Path.Combine(Directory.GetCurrentDirectory(), "PDF-FILE.pdf");
Process P = new Process {
StartInfo = {FileName = "AcroRd32.exe", Arguments = path}
};
P.Start();
In order for this to work, the Visual Studio setting Copy to Output Directory has to be set to Copy Always for the PDF file.

If the only point of the PDF is to be opened by a PDF reader, don't embed it as a resource. Instead, have your installation copy it to a reasonable place (you could put it where the EXE is located), and run it from there. No point in copying it over and over again.

"ReferenceGuide" is the name of the pdf file that i added to my resources.
using System.IO;
using System.Diagnostics;
private void OpenPdfButtonClick(object sender, EventArgs e)
{
//Convert The resource Data into Byte[]
byte[] PDF = Properties.Resources.ReferenceGuide;
MemoryStream ms = new MemoryStream(PDF);
//Create PDF File From Binary of resources folders helpFile.pdf
FileStream f = new FileStream("helpFile.pdf", FileMode.OpenOrCreate);
//Write Bytes into Our Created helpFile.pdf
ms.WriteTo(f);
f.Close();
ms.Close();
// Finally Show the Created PDF from resources
Process.Start("helpFile.pdf");
}

File.Create("temp path");
File.WriteAllBytes("temp path", Resource.PDFFile)

You need to convert the resource into format acceptable for the program supposed to consume your file.
One way of doing this is to write the content of the resource to a file (a temp file) and then launch the program pointing it to the file.
Whether it is possible to feed the resource directly into the program depends on the program. I am not sure if it can be done with the Adobe Reader.
To write the resource content to a file you can create an instance of the MemoryStream class and pass your byte array to its constructor

This should help - I use this code frequently to open various executable, documents, etc... which I have embedded as a resource.
private void button1_Click(object sender, EventArgs e)
{
string openPDFfile = #"c:\temp\pdfName.pdf";
ExtractResource("WindowsFormsApplication1.pdfName.pdf", openPDFfile);
Process.Start(openPDFfile);
}
void ExtractResource( string resource, string path )
{
Stream stream = GetType().Assembly.GetManifestResourceStream( resource );
byte[] bytes = new byte[(int)stream.Length];
stream.Read( bytes, 0, bytes.Length );
File.WriteAllBytes( path, bytes );
}

//create a temporal file
string file = Path.GetTempFileName() + ".pdf";
//write to file
File.WriteAllBytes(file, Properties.Resources.PDF_DOCUMENT);
//open with default viewer
System.Diagnostics.Process.Start(file);

Related

Save all contents in ListBox to .txt file

I am trying to save all contents in a ListBox to a .txt file. I have the following code:
private void btn_Save_Click(object sender, EventArgs e)
{
const string sPath = "save.txt";
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
SaveFile.WriteLine(listBox1.Items);
SaveFile.ToString();
SaveFile.Close();
MessageBox.Show("Programs saved!");
}
But when I test it the code works but and it acts like it saved the file but when I go into my File Explorer, I cannot see the file anywhere.
Does anyone have any answers
You need to provide the explicit path. Example:
const string sPath = #"C:\MyFolder\save.txt";
What u have to do?
First:
You need a StreamWriter, u done it right. This StreamWriter needs a Path, you did this too.
Second:
You want all Items of your listbox, so use foreach. You havent done this.
Third: Close the Stream, you done it too. Use using instead of close , its better :) do the same :)
Where i find the file? Go to your Project right in Visual Studio right click on it -> open in windows explorer -> bin -> Debug and your text file is their. If you dont give a absolute path, the saved data is always next to your .exe.
Solution:
string path = "save.txt";
using (StreamWriter sw = new StreamWriter(path))
{
foreach (string s in listBox1.Items)
{
sw.WriteLine(s);
}
};

Open CHM File from Resources c#

I have a CHM file and a help menu and I want to add that file to resources but when I added it to resources it does not work.
I tried to add to subfolder in Resources but still no use
void HelpToolStripMenuItemClick(object sender, EventArgs e)
{
string filePath = Directory.GetCurrentDirectory() + "\\Help\\abc.chm";
try
{
//Check if already exists before making
if (!File.Exists(filePath))
{
var data = Properties.Resources.abc.chm;
using (var stream = new FileStream("abc.chm", FileMode.Create))
{
stream.Write(data, 0, data.Count());
stream.Flush();
}
MessageBox.Show("file made");
}
}
catch
{
//May already be opened
}
Help.ShowHelp(this, filePath);
}
I want to work even when this to work even when the setup is installed
on any computer
I would be better if any tells how to embedded in my setup
First of all, add the help file to your project and open the Properties window for that file. In the CopyToOutputDirectory, choose ‘Copy always’ or ‘Copy if newer’.
This will make sure, that when you’re debugging/testing your application, that it will copy the file to the bin folder.
Start your project in Debug mode and check your bin/debug output folder. Do the same for Release mode and output folder. The CHM should reside there and gets included in your deployment.
A sample code snippet for calling CHM's:
private const string sHTMLHelpFileName = "CHM-example.chm";
...
private void button1_Click(object sender, EventArgs e) {
System.Windows.Forms.Help.ShowHelp(this, Application.StartupPath + #"\" + sHTMLHelpFileName);
}
For download I provide a C# VS2008 Project including the code above and the help files with different help viewer windows (different CHM files for show case only).

"Saving" directly to Clipboard - Possible?

I'm working with an API that produces images in BMP or JPG format. The API method in question requires a path and filename. However, in some cases, I would like to simply put the image into the Clipboard.
I know I can save to a file, then open the file and copy the Stream's data to the Clipboard:
private void SaveSnapshot(string path)
{
var pathWasblank = path.IsNullOrBlank();
path = path.NullIfBlank() ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),"tempFile.jpg");
myApiInstance.ExportJPG(path, 100, true);
//to ensure the file has made it to the filesystem
while(!File.Exists(path)) Thread.Sleep(100);
if (pathWasblank) //it should be on the Clipboard and not in a file
{
using (var stream = File.OpenRead(path))
Clipboard.SetImage(Image.FromStream(stream));
File.Delete(path); //cleanup;
}
}
What I want to know is if there is a way to skip having to reopen, copy and then delete the file, and instead "save" directly to the Clipboard by specifying some file path that corresponds to the Clipboard. If not, no big deal; I have a working solution.

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.

Embed a Word Document in C#

I want to open a MS Word document from my program. At the moment, it can find it when in designer mode but when i publish my program it can't find the file. I believe I need to embed it into my program but I don't know how to do this. This is my current code to open the document:
System.Diagnostics.Process.Start("Manual.docx");
I think the Word document needs to be embedded into the resources of the .exe but i don't know how to to do this.
Can anyone help with some suggestions?
Aaron is pretty right on adding an embedded resource. Do the following to access an embedded resource:
Assembly thisAssembly;
thisAssembly = Assembly.GetExecutingAssembly();
Stream someStream;
someStream = thisAssembly.GetManifestResourceStream("Namespace.Resources.FilenameWithExt");
More info here:
How to embed and access resources by using Visual C#
Edit: Now to actually run the file you will need to copy the file in some temp dir. You can use the following function to save the stream.
public void SaveStreamToFile(string fileFullPath, Stream stream)
{
if (stream.Length == 0) return;
// Create a FileStream object to write a stream to a file
using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
{
// Fill the bytes[] array with the stream data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
Right click the folder where you want to store the file within the Solution and choose Add -> Existing Item.
Once you add the file you can change the Build Action of the file within your project to be an Embedded Resource, versus a Resource. This can be done by going to the Properties within VS of the file and modifying the Build Action property.
Just include it to your project (add existing item) and from the menu that opens, select all files and select your word document. Also Copy the document into your Bin/Debug folder. If you are using an installer, include the document in the installer and it should work.

Categories

Resources