[英]Folder of running application
我的C#應用程序有問題,通過文件關聯打開時,它在文件目錄中有效。 例如,當我創建打開文件的副本時:
File.Copy("C:\Photo\car.jpg", ".\car2.jpg"); // this is only ilustration code.
它創建了新文件“ C:\\ Photo \\ car2.jpg”,但我想在我的應用程序目錄中創建文件(“。\\ car2.jpg”)。
因此,我認為,當通過文件關聯打開應用程序時,它將在該文件的工作文件夾(“ C:\\ Photo \\”)下運行。 有沒有辦法,如何使用app.exe將工作目錄保留為目錄?
編輯:
這不是解決方案,我需要等於“。\\”和System.AppDomain.CurrentDomain.BaseDirectory:
File.Copy("C:\Photo\car.jpg", Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "car2.jpg"));
我必須在應用程序中的許多地方使用它,可以設置解決方案:
Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
但是我更喜歡通過文件關聯而不是在運行的程序中在啟動應用程序中設置它-看起來更干凈。
謝謝,雅庫布
要獲取應用程序的路徑,可以使用:
System.AppDomain.CurrentDomain.BaseDirectory
使用Path.Combine
如下構建目標路徑:
File.Copy("C:\Photo\car.jpg", Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "car2.jpg"));
我想嘗試提供替代方法。 我相對較新,但是我想出了一個對我有用的解決方案:
在MainWindow.xaml.cs中創建2個靜態變量:
public static string fileOpen;
public static string workingDirectory;
在您的app.xaml.cs文件中,添加以下代碼:
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Count() > 0)
{
var a = File.Exists(e.Args[0]);
var path = Path.GetFullPath(e.Args[0]);
MainICPUI.workingDirectory = Directory.GetCurrentDirectory();
MainICPUI.fileOpen = e.Args[0];
}
base.OnStartup(e);
}
當您從任何目錄打開與程序關聯的文件時,完整的文件名將添加到StartupEventArgs(包括目錄)中。 此代碼保存目錄。
返回您的MainWindow.xaml.cs文件:
public static string fileOpen;
public static string workingDirectory;
public MainWindow()
{
InitializeComponent();
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
// This sets the directory back to the program directory, so you can do what you need
// to with files associated with your program
}
// Make sure your MainWindow has an OnLoaded event assigned to:
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
// Now I'm setting the working directory back to the file location
Directory.SetCurrentDirectory(workingDirectory);
if (File.Exists(fileOpen))
{
var path = Path.GetFullPath(fileOpen);
// This should be the full file path of the file you clicked on.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.