简体   繁体   中英

How to get directory of an xls file C#

I need to make a program that reads the columns of an excel. But for that, I need to get the path (directory) of this excel. What prevents me from doing this, is that I didn't want to leave my local directory fixed, because if someone downloads the file on another machine, they will need to change the path.

在此处输入图像描述

You have two options:

  1. If you don't want to your excel files to be stored in your application's directory, you can simply put things in the root of your C: partition. Every windows device is gonna have the C: partition. As the user Lee Taylor has pointed out, it turns out you can have a windows device without the C: partition, although uncommon
  2. If you don't mind having your excel files stored in your application's directory, you can get the relative path of your application's directory through Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

There are other ways but I believe these are the simplest and easiest to do.

You asked How to get directory of an xls file C# .

As others have pointed out, the file needs to be in a known location and one way to do that is to add the Excel file to your solution and mark it as Content , specifying that it should be copied to the output directory. The image below shows how to set these properties.

You also seem to be looking for a robust way to make this happen when you deploy the app for other users. For this, you will need a strategy for making an .msi or .msix that will place this file where it needs to be. But to answer your basic question the way you asked it the path in this case can be obtained in this manner. This code will get the path and open the Excel file.

// Get the path and open the Excel file
static void Main(string[] args)
{
    var path =  
        Path.Combine(
            Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), 
            "Microsoft Excel Worksheet.xlsx");

    Console.WriteLine(path);
    System.Diagnostics.Process.Start("explorer.exe", path);
}

在此处输入图像描述

I should mention that a file in the executing directory can be read but not written (without elevated permissions). If the file is user data then refer to the answer that uses an Environment variable:

var appdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

If you just need to dynamically get the path to a file that is in the same project directory, then the following code works for me -

string filePath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\excel\\Prices.xlsx";

where "\excel" is the folder in my project and "\Prices.xlsx" the file in the project

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