WinForms如何在资源文件夹中打开文件
WinForms如何在资源文件夹中打开文件
我是WinForms技术的新手。我正在使用.NET Framework 4.8和Microsoft Visual Studio 2019。我将文件放在Resources
文件夹中。
我尝试了以下代码:
using DevExpress.XtraBars; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace accwf { public partial class NhapSoDu : DevExpress.XtraBars.Ribbon.RibbonForm { public NhapSoDu() { InitializeComponent(); } private void simpleButton1_Click(object sender, EventArgs e) { Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory); Process.Start(".../B01-DN_01_Summary.xlsx"); } } }
请指导我完成它。
问题出现的原因是程序当前只输出基本目录,并且只在该基本目录中查找文件。执行发生在基本目录中,因此程序在寻找“..\Path\to\exe\B01-DN_01_Summary.xlsx”时实际上应该寻找“..\Path\to\exe\Resources\FilesHere\ImportExcel\B01-DN_01_Summary.xlsx”。
嵌入资源文件到应用程序中并不推荐。更好的方法是存储它们的位置,并允许应用程序在目录中查找指定的文件位置。
以下是一个适应的版本,你可以尝试一下:
你需要确保你所需文件的“复制到输出目录”属性设置为“始终复制”或“如果更新则复制”。这将确保目录路径在输出目录中创建。
namespace accwf { public partial class NhapSoDu : DevExpress.XtraBars.Ribbon.RibbonForm { public NhapSoDu() { InitializeComponent(); } private void simpleButton1_Click(object sender, EventArgs e) { string resourcePath = System.IO.File.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Resources\\FilesHere\\ImportExcel\\B01-DN_01_Summary.xlsx"); if (File.Exists(resourcePath)) { MessageBox.Show("Exists"); } else { MessageBox.Show("Doesn't Exist"); } Process.Start(resourcePath); } } }
这是一个我从帮助菜单中获取PDF文件文档的示例:
public void MyMethod() { // helpMenuPath是一个全局变量,设置为类似于:Area/MyApp/Resources/ string filePath = helpMenuPath; string[] fileNames = new string[0]; // 将变量初始化为长度为0。Directory.GetFiles()将允许重写这个长度 // 尝试/捕获错误处理 try { fileNames = Directory.GetFiles(filePath); } catch (IOException ioe) { // 如果目录不正确,则捕获错误 MessageBox.Show($"Error in getting files: {ioe.Message}"); } // 对文件进行处理... }
第一个代码片段导致错误,第二个代码片段是我使用WinForms而不是ASP.NET Core的示例。
第二个代码片段是在ASP.NET Core中使用的,但我将其提供作为一个例子。我修改了第二个代码片段,使其更适合WinForms。
问题出现的原因:用户想要在WinForms应用程序中打开一个嵌入资源文件夹中的文件(这里是一个XLSX文件),但不知道如何实现。
解决方法:用户可以按照下面的步骤来解决问题。
首先,需要在代码中引用System.IO命名空间,以便可以访问MemoryStream和FileStream类。
然后,在事件处理方法中,可以使用以下代码来打开嵌入资源文件夹中的文件:
private void buttonOpenTemplate_Click(object sender, EventArgs e) { byte[] templateFile = Properties.Resources._01__So_du_tai_khoan; // 这是应用程序资源中的Excel文档 string tempPath = $"{Path.GetTempFileName()}.xlsx"; using (MemoryStream ms = new MemoryStream(templateFile)) { using(FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate)) { ms.WriteTo(fs); fs.Close(); } ms.Close(); } Process.Start(tempPath); }
上述代码首先将嵌入资源文件转换为字节数组,然后使用MemoryStream将字节数组写入到临时文件中。最后,使用Process.Start方法打开临时文件。
值得注意的是,此代码假设应用程序中存在名为"_01__So_du_tai_khoan"的资源文件,并且将临时文件的扩展名设置为.xlsx。用户可以根据实际情况修改这些值。
通过按照以上步骤操作,用户就可以在WinForms应用程序中打开嵌入资源文件夹中的文件了。
(完)