我是Visual Studios的新手,我正在尝试创建一个创建.ahk文件的应用程序。我的问题是,当应用程序启动时,我需要它来创建几个文件/文件夹。要做到这一点,我添加了这段代码
public MainWindow()
{
InitializeComponent();
int i = 1;
while (i < 6)
{
string comp_name = System.Environment.UserName;
System.IO.File.Create(@"C:\Users\" + comp_name + @"\Documents\KeyBind\" + i + @"\Modifier.txt");
System.IO.File.Create(@"C:\Users\" + comp_name + @"\Documents\KeyBind\" + i + @"\Key.txt");
System.IO.File.Create(@"C:\Users\" + comp_name + @"\Documents\KeyBind\" + i + @"\Me_Do.txt");
System.IO.File.Create(@"C:\Users\" + comp_name + @"\Documents\KeyBind\" + i + @"\Text.txt");
System.IO.File.Create(@"C:\Users\" + comp_name + @"\Documents\KeyBind\" + i + @"\Bind" + i + @".txt");
System.IO.File.Create(@"C:\Users\" + comp_name + @"\Documents\KeyBind\Bind.ahk");
i++;
}
}
这导致以下错误
> An unhandled exception of type
> 'System.Windows.Markup.XamlParseException' occurred in
> PresentationFramework.dll
>
> Additional information: 'The invocation of the constructor on type
> 'WpfApplication2.MainWindow' that matches the specified binding
> constraints threw an exception.' Line number '3' and line position
> '9'.
不确定这里的问题是什么。 如果你想查看我在这里的完整代码是链接Full Code 我知道有很多冗余代码我打算修复它,一旦我弄清楚了。任何帮助表示赞赏。
答案 0 :(得分:0)
尽量不要使用硬编码的文档路径,也不要尝试创建已存在的目录。您也可能不想创建文件,除非它们丢失。
private void EnsureFiles()
{
var numberedFiles = new[] { "Modifier.txt", "Key.txt", "Me_Do.txt", "Text.txt" };
var basePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"KeyBind");
if (!Directory.Exists(basePath))
Directory.CreateDirectory(basePath);
var bindAhkPath = Path.Combine(basePath, "Bind.ahk");
if (!File.Exists(bindAhkPath))
File.CreateText(bindAhkPath).Dispose();
for (var i = 1; i < 6; i++)
{
foreach (var file in numberedFiles)
{
var numberedPath = Path.Combine(basePath, i.ToString());
if (!Directory.Exists(numberedPath))
Directory.CreateDirectory(numberedPath);
var filePath = Path.Combine(numberedPath, file);
if (!File.Exists(filePath))
File.CreateText(filePath).Dispose();
}
}
}
正如其他人所建议的那样,您可能希望将此方法移出主窗口并移至App
课程,然后重写OnStartup
进行调用。