本文介绍了在项目C#WPF中找不到文件夹路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将gridview导出到excel,我将其保存在我的项目中的文件夹中,之后我将设置密码到excel文件。



问题是我找不到路径



错误:



抱歉,我们找不到../../files/Test.xlsx。它是否可能被移动,重命名或删除?



我尝试过:



I am exporting my gridview to excel and i am saving it in the folder which is in my project and after that i am setting a password to the excel file.

Problem is i cannot find the path

ERROR:

Sorry, we couldn't find ../../files/Test.xlsx. Is it possible it was moved, renamed or deleted?

What I have tried:

 public static void Setpassword()
        {           
            string filename = "../../files/Test.xlsx";
            string password = "1245";

            if (!File.Exists(filename))
                return;

            Microsoft.Office.Interop.Excel.Application oexcel;
            Microsoft.Office.Interop.Excel.Workbook obook;

            oexcel = new Microsoft.Office.Interop.Excel.Application();
            oexcel.DisplayAlerts = false;
           
            obook = oexcel.Workbooks.Open(filename, 0, false, 5, "", "", true, System.Reflection.Missing.Value, "\t", false, false, 0, true, 1, 0);

//ERROR : Sorry, we couldn't find ../../files/Test.xlsx. Is it possible it was moved, renamed or deleted?

            try
            {
                obook.SaveAs(filename, Password: password, ConflictResolution: Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges);
            }
            finally
            {
                obook.Close();
                oexcel.Quit();
            }
        }

推荐答案

string filename = Environment.CurrentDirectory + "\Test.xlsx";
//Environment.CurrentDirectory - represents the current working directory of the project.



或者您也可以使用它,


Or you can use this also,

string filename = AssemblyDirectory + "\Test.xlsx";

public static string AssemblyDirectory
{
   get
   {
      string codeBase = Assembly.GetExecutingAssembly().CodeBase;
      UriBuilder uri = new UriBuilder(codeBase);
      string path = Uri.UnescapeDataString(uri.Path);
      return Path.GetDirectoryName(path);
   }
}
//Here AssemblyDirectory is a string property, which also represents the directory of the current project.


这篇关于在项目C#WPF中找不到文件夹路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 01:43