我无法从项目目录导入。这是我的代码:
FileDialog file = new OpenFileDialog();
file.InitialDirectory = @"";
file.Filter = "txt files (*.txt)|*.txt";
file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK && this.mAT != null)
{
if (file.FileName != String.Empty || file.FileName != null)
return this.mAT.importFromLexiconFile(file.FileName);
}
else return false;
return false;
如何使用目录作为something.txt
等文本从本地目录导入文件,而不是在FileDialog
中查找文件?
答案 0 :(得分:1)
您可以使用以下命令获取项目开始的目录:
Environment.CurrentDirectory;
或者,您可以使用以下内容获取.exe
所在的位置:
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
在运行时,这将是:
C:\项目\ MyApplication的\ myproject的\ BIN \调试\
以下是如何找到您的文件,以及您可以使用它做的一些不同的事情。不确定你想要做什么:
private static void Main()
{
// The directory to search for the file
var searchPath = Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location);
// The name of the file we're searching for
var fileName = "MyFile.txt";
// Get the first match
var theFile = Directory.GetFiles(searchPath, fileName).FirstOrDefault();
// If the match is not null, we found the file
if (theFile != null)
{
// Output some information about the file
Console.WriteLine("Found the file: {0}", fileName);
Console.WriteLine("The full path of the file is: {0}", theFile);
// If it's a text file, here's one way to get the contents
var fileContents = File.ReadAllText(theFile);
Console.WriteLine("The contents of the file are:{0}{1}", Environment.NewLine,
fileContents);
// If you need detailed info about the file, or
// want to write to it, create a FileInfo object
var fileInfo = new FileInfo(theFile);
// Output some detailed information about the file
Console.WriteLine("The file was created on: {0}", fileInfo.CreationTime);
Console.WriteLine("The file was last modified on: {0}",
fileInfo.LastWriteTime);
Console.WriteLine("The file attributes are:");
Console.WriteLine(" - ReadOnly: {0}",
Convert.ToBoolean(fileInfo.Attributes & FileAttributes.ReadOnly));
Console.WriteLine(" - Hidden: {0}",
Convert.ToBoolean(fileInfo.Attributes & FileAttributes.Hidden));
Console.WriteLine(" - System: {0}",
Convert.ToBoolean(fileInfo.Attributes & FileAttributes.System));
}
}