简体   繁体   中英

How to access the files in bin/debug within the project folder in Visual studio 2010?

I have my docx.xsl file in my project/bin/debug folder.Now i want to access this file whenever i needed.But i could not able to access this file.

 WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFile, true);
 MainDocumentPart mainDocPart = wordDoc.MainDocumentPart;
 XPathDocument xpathDoc = new XPathDocument(mainDocPart.GetStream());
 XslCompiledTransform xslt = new XslCompiledTransform();

 string xsltFile = @"\\docx.xsl"; // or @"docx.xsl";

 xslt.Load(xsltFile);
 XmlTextWriter writer = new XmlTextWriter(outputFile, null);
 xslt.Transform(xpathDoc, null, writer);
 writer.Close();
 wordDoc.Close();

Please Guide me to put correct valid path to access docx.xsl file...

You can determine the location of your executable, and assuming the file will be deployed with the application to the relevant directory, then this should help you find the file in debugging and in deployment:

string executableLocation = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().Location);
string xslLocation = Path.Combine(executableLocation, "docx.xsl");

You might need the following namespaces imported at the top of your file:

using System;
using System.IO;
using System.Reflection;

If you add the file as resource you don't need to deal with paths at runtime.

  • Add the file to the visual studio project and set the build action to "Embedded Resource".

The name of the resource is the project default namespace + any folders just like any code file in the project.

string resourceName = "DefaultNamespace.Folder.docx.xsl";

If you have the code in the same folder you can do like this

string resourceName = string.Format("{0}.docx.xsl", this.GetType().Namespace);
  • Then you read the file using a resource stream Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)

In your case, it would look like this:

using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (var reader = XmlReader.Create(stream))
    xslt.Load(reader);

Application.StartupPath gives you the full path upto bin/debug.

So what you need to do is:

string xsltFile =Application.StartupPath + @"\\docx.xsl";

In order to access file from Bin/Debug folder you only have to specify file name. See below

xslt.Load("docx.xsl");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM