Using embedded resources in C# console application - c#

I'm trying to embed an XML file into a C# console application via Right clicking on file -> Build Action -> Embedded Resource.
How do I then access this embedded resource?
XDocument XMLDoc = XDocument.Load(???);
Edit: Hi all, despite all the bashing this question received, here's an update.
I managed to get it working by using
XDocument.Load(new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Namespace.FolderName.FileName.Extension")))
It didn't work previously because the folder name containing the resource file within the project was not included (none of the examples I found seemed to have that).
Thanks everyone who tried to help.

Something along these lines
using System.IO;
using System.Reflection;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.XMLFile1.xml");
StreamReader reader = new StreamReader(stream);
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
}
}
}
Here is a link to the Microsoft doc that describes how to do it. http://support.microsoft.com/kb/319292

Related

Having permission issues when using itext7 to convert PNG files to PDFs, some commands seems to have access others dont

https://itextpdf.com/en/demos/convert-image-to-pdf-free-online
I got the demo code on how to do it from their site, I am building this in c# visual studio, with selenium/ nunit
It seems pretty straight forward, but im getting some issue that I dont understand. Here is my code:
using System;
using iText.IO.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace TesingPDFConvert
{
internal class Program
{
private static string ORIG = #"C:\Users\$username\Documents\c_projects\SeleniumScreenshots";
private static string OUTPUT_FOLDER = #"C:\Users\$username\Documents\c_projects\pdf_output\";
public static void Main(string[] args)
{
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(OUTPUT_FOLDER + "ImageToPdf.pdf"));
Document document = new Document(pdfDocument);
ImageData imageData = ImageDataFactory.Create(ORIG);
Image image = new Image(imageData);
image.SetWidth(pdfDocument.GetDefaultPageSize().GetWidth() - 50);
image.SetAutoScaleHeight(true);
document.Add(image);
pdfDocument.Close();
}
}
}
When I run this, I am getting access denied to the SeleniumScreenshots folder, but the other folder (pdf_output) seems to have access. If i change the folder to the pdf_output folder to get the images from there, im still getting access denied, however, it is writing the empty pdf to the output folder so it seems to have access. I tried changing the folders from "Read only" attribute but its not saving for some reason, I dont think thats the issue cause ive written to my documents folder in other selenium or c# projects and havent had issues. My thoughts are that im using itext7 wrong.
The goal here is to get grab the PNGs in my SeleniumScreenshots folder and turn them into a PDF and drop in the pdf_outputs folder after running a selenium/nunit test(not seen in code).
After not being able to get it to work with my selenium/nunit project, I opened a new project and set up their code to work(console application) and still had the same results. Im stumped.
I am pretty new to c# and visual studio code/developement in general. Thanks for any help in advance.
According to the comment, the solution is as follows:
ORIG is a file name at the end, you can’t refer to the folder.
OUTPUT_FOLDER last refers to the space under the folder, you are missing \.
There is no problem with the code itself.

C#: StreamWriter program is not writing to text file

I know this question has probably been answered multiple times across this site, but even after looking at those solutions I don't have an answer to why my program isn't writing to the text file I have assigned. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Main
{
class Program
{
public static void Main (string[] args)
{
using (StreamWriter writer = new StreamWriter("test.txt"))
{
writer.WriteLine("Hello, World!");
}
}
}
}
My program throws no exceptions and exits with 0, so I am not understanding how this is still not functioning properly. If someone could please provide an answer along with an explanation as to why this doesn't work, I would really appreciate it.
EDIT: Okay, I fixed the code after playing around a bit. Turns out that upon reading the file the text that I wrote is there. Thus, a clarification of this problem would be:
The text writes to the file, but it is not visible to me when I open up the file from my project in Visual Studio. I am not sure as to why, and this is leading to confusion
Your sample is correct. The file is saved into build path. (where is "yourApp.exe").
You can try with a abosule path to define where file will be save, for example StreamWriter writer = new StreamWriter(#"c:\test\test.txt")

XmlDocument missing Load method in .Net Core?

I'm creating a Console App, .Net Core 1.1, and am trying to read an XML file. I brought in the System.Xml.XmlDocument nuGet package, created an XmlDocument, and then attempted to load using the file name. To my surprise, there is no overload for Load(string). See the attached image from the object browser. Is this permanently gone? I tried finding documentation, but was unsuccessful and mainly just found information like here
using System;
using System.Xml;
using System.Xml.Linq;
namespace ReadingXmlDemo
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
string content =
doc.Load("Example.xml");
The XmlDocument.Load(string) method is part of .NET Core 2.0 and .NET Standard 2.0. For .NET Core 1.*, you'll need to use the Load(Stream) method and pass it FileStream obtained via File.Open.
You can check the availability of the method at API .NET Catalog for System.Xml.XmlDocument.Load(String)
see simple exemple:
string sourceFileXML = #"c:\temp\file.xml";
var xml = new XmlDocument();
using (var sr = new StreamReader(sourceFileXML)) {
xml.Load(sr);
}

PowerTools for OpenXml. Null reference when reading header/footer

i've got a task to convert docx document to Pdf. I've decided to take this approach:
convert docx to html, then pass html to ItextSharp. Few week i've been looking all over google, codeplex, sourceforge and stackoverflow and so on for a solution thow to make this conversion, until I found Eric White blog. At firs impression he made great tool for working with OpenXml documents. But when I tried to test it I've got an error about null reference. Error occurs when reading header (RevisionAccepter class)
public static void AcceptRevisions(WordprocessingDocument doc)
{
AcceptRevisionsForPart(doc.MainDocumentPart);
foreach (var part in doc.MainDocumentPart.HeaderParts) //part is null
AcceptRevisionsForPart(part); //null ref exception here
foreach (var part in doc.MainDocumentPart.FooterParts)
AcceptRevisionsForPart(part);
if (doc.MainDocumentPart.EndnotesPart != null)
AcceptRevisionsForPart(doc.MainDocumentPart.EndnotesPart);
if (doc.MainDocumentPart.FootnotesPart != null)
AcceptRevisionsForPart(doc.MainDocumentPart.FootnotesPart);
}
code I use for conversion (same as in example)
private void conv()
{
byte[] byteArray = File.ReadAllBytes(textBox1.Text);
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(byteArray, 0, byteArray.Length);
using (WordprocessingDocument doc =
WordprocessingDocument.Open(memoryStream, true))
{
HtmlConverterSettings settings = new HtmlConverterSettings()
{
PageTitle = "My Page Title"
};
XElement html = HtmlConverter.ConvertToHtml(doc, settings);
File.WriteAllText("Test.html", html.ToStringNewLineOnAttributes());
}
}
}
nameSpaces:
using System.Xml;
using System.Xml.Xsl;
using OpenXmlPowerTools;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
I tried to pass documents created by word 2010, with header and without and still getting errors in the same place. Maybe I'm passing document incorrectly or something with the document itself.
Maybe there is another way to convert docx to pdf without using comercial components, like Apose.
found the problem. Errors was occuring because of different references between power tools project and main project.
DocumentFormat.OpenXml version on my project was 2.5.5513.0 and on power tools - 2.0.5022.0
After making references to the same resource everything went fine.

PDF files with XML files attached

HI All,
I have a PDF file with a xml attached, i need to parse the xml file. Does anyone knows how i do that?
I´m using C#.
Thanks in advance.
I believe this blog post describing how read from a PDF file using C# is what you want.
This is the example he gives of grabbing text from the PDF:
using System;
using org.pdfbox.pdmodel;
using org.pdfbox.util;
namespace PDFReader
{
class Program
{
static void Main(string[] args)
{
PDDocument doc = PDDocument.load("lopreacamasa.pdf");
PDFTextStripper pdfStripper = new PDFTextStripper();
Console.Write(pdfStripper.getText(doc));
}
}
}
Here is what looks like an exhaustive and highly organized list of how to read PDFs with C#.
If what you need is some form of embedded meta data, as Mark suggested, I'm sure it's also possible with the to fetch using the tools I've linked to.
Try using LINQ to XML as suggested in this question.
PDF files can have a meta data information object or is it an XML file embedded as an object?

Categories