如何在Visual Studio 2010中的项目文件夹中访问bin/debug中的文件?

Sar*_*nan 18 .net c# visual-studio-2010

我在我的project/bin/debug文件夹中有我的docx.xsl文件.现在我想在需要时访问此文件.但是我无法访问此文件.

 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();
Run Code Online (Sandbox Code Playgroud)

请指导我输入正确的有效路径来访问docx.xsl文件...

Gra*_*mas 40

您可以确定可执行文件的位置,并假设文件将与应用程序一起部署到相关目录,这样可以帮助您在调试和部署中找到该文件:

string executableLocation = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().Location);
string xslLocation = Path.Combine(executableLocation, "docx.xsl");
Run Code Online (Sandbox Code Playgroud)

您可能需要在文件顶部导入以下命名空间:

using System;
using System.IO;
using System.Reflection;
Run Code Online (Sandbox Code Playgroud)

  • 但是如果文件被物理地放入〜\ Bin文件夹,那么上面将如何访问呢?我说的是asp.net web项目而不是Windows部署. (3认同)

adr*_*anm 10

如果将文件添加为资源,则无需在运行时处理路径.

  • 将文件添加到visual studio项目并将构建操作设置为"Embedded Resource".

资源的名称是项目默认名称空间+任何文件夹,就像项目中的任何代码文件一样.

string resourceName = "DefaultNamespace.Folder.docx.xsl";
Run Code Online (Sandbox Code Playgroud)

如果您将代码放在同一文件夹中,则可以执行此操作

string resourceName = string.Format("{0}.docx.xsl", this.GetType().Namespace);
Run Code Online (Sandbox Code Playgroud)
  • 然后使用资源流读取文件 Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)

在你的情况下,它看起来像这样:

using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (var reader = XmlReader.Create(stream))
    xslt.Load(reader);
Run Code Online (Sandbox Code Playgroud)