[英]How to retrieve Excel file inside project folder?
使用以下代码,我可以将Book1.xlsx文件从Application 文件夹复制到Desktop 。
vb.net版
Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
IO.File.Copy(sourceFileName:=IO.Path.Combine(New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName).DirectoryName, "Book1.xlsx"),
destFileName:=My.Computer.FileSystem.SpecialDirectories.Desktop & "\Book1.xlsx")
End sub
C#版
private void Button1_Click(object sender, RoutedEventArgs e)
{
System.IO.File.Copy(sourceFileName: System.IO.Path.Combine(new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().FullName).DirectoryName, "Book1.xlsx"),
destFileName: My.Computer.FileSystem.SpecialDirectories.Desktop + @"\Book1.xlsx");
}
请按照以下方式将Book2.xlsx文件放入项目文件夹:添加 > 现有项目
如何从项目文件夹中复制Book2.xlsx文件并粘贴到桌面?
我的问题摘要在这里:
我可以将Book1.xlsx文件从Application 文件夹复制到Desktop 。
如何将Book2.xlsx文件从Project 文件夹复制到Desktop 。
请按照以下方式将 Book2.xlsx 文件放入项目文件夹:添加 > 现有项目
如何从项目文件夹中复制 Book2.xlsx 文件并粘贴到桌面?
我的问题摘要在这里:
我可以将 Book1.xlsx 文件从 Application 文件夹复制到桌面。
如何将 Book2.xlsx 文件从 Project 文件夹复制到桌面。
在 WPF 中,您需要使用Pack URI来访问您所做的文件,就像“通过以下方式将 Book2.xlsx 文件放入项目文件夹:添加 > 现有项目”
并将 Book2.xlsx Build Action 设置为 'Resource' 。 然后,尝试以下代码。
private void Button_Click(object sender, RoutedEventArgs e)
{
string excelPath = "pack://application:,,,/Xbook2.xlsx";
StreamResourceInfo excelInfo = System.Windows.Application.GetResourceStream(new Uri(excelPath));
using (Stream file = File.Create(@"D:\Xbook2.xlsx"))
{
CopyStream(excelInfo.Stream, file);
}
//System.IO.File.Copy(excelInfo.Stream., @"D\Xbook2.xlsx");
}
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
编译和运行的应用程序没有项目或项目文件夹的概念或知识。 这是用于构建应用程序的源文件所在的文件夹。 它可能位于另一台计算机上。
因此,如果您需要在运行时从项目文件夹中复制某些内容,则需要对其路径进行硬编码:
System.IO.File.Copy(sourceFileName: @"c:\Users\x\your_project_folder\Book1.xlsx",
destFileName: My.Computer.FileSystem.SpecialDirectories.Desktop + @"\Book1.xlsx");
无法从编译的可执行文件中解决它。
根据目录树,我假设您的项目路径以这样的方式结束
SolutionFolder\ProjectFolder\bin\Debug
在这种情况下,您需要将 go 向后退 2 步,这将需要这样的东西
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
desktopPath += "\\" + @"\Book1.xlsx";
string fileSource = Path.GetFullPath(Path.Combine(System.IO.Path.Combine(new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().FullName).DirectoryName, ""), @"..\..\Book1.xlsx"));
System.IO.File.Copy(fileSource, desktopPath);
因此,如果您想 go 再次返回第三步,您将更改
@"..\..\Book1.xlsx"
至
@"..\..\..\Book1.xlsx"
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.