尝试奉献的文件在一个固定的子目录:
\ TicTacToe.exe \设置\ settings.cfg
所以路径取决于您的可执行文件。
你会通过调用Directory.GetCurrentDirectory()
取目录,您可以通过设置Environment.CurrentDirectory
来处理这种情况的一种常见方式设置所需的目录上面所描述的。
另一种方法是使用用户指定的目录,如%appdata%路径并在那里创建一个专用目录。
%APPDATA%\井字游戏\ settings.cfg
每次应用程序启动时,它应该查找的文件夹%APPDATA%\井字游戏\
如果它存在,你的应用程序已经与该用户执行。 如果没有,只需创建一个新的,所以我们知道这是第一次运行。
你可以通过调用什么,我会做
private void setUp(){
string filename = "settings.cfg";
string dir = "TicTacToe";
string appdata =Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullpath = Path.Combine(Path.Combine(appdata,dir),filename);
//check if file exists, more accurate than just looking for the folder
if(File.Exists(fullpath)){
//read the file and process its content
}else{
Directory.CreateDirectory(Path.Combine(appdata,dir)); // will do nothing if directory exists, but then we have a bug: no file, but directory available
using (FileStream fs = File.Create(fullpath))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
}
希望它帮助
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
范例中得到%APPDATA%路径。
那么你想搜索整个硬盘? –
许多文件可以具有相同的名称,因此您必须知道在哪里查找。 – buffjape
您是否认为“CurrentDirectory”会在程序运行的任何地方?因此,如果您将文件复制到驱动器的根目录,那么它可能会在那里? –