[英]C# WPF - Error when trying to create files on app start-up
I am new to Visual Studios, I am trying to make an app that create an .ahk file. 我是Visual Studios的新手,我正在尝试制作一个创建.ahk文件的应用程序。 My problem is that when the app starts up I need it to create several files/folders.
我的问题是,当应用启动时,我需要它来创建多个文件/文件夹。 to do this I added this code
为此,我添加了此代码
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++;
}
}
this results in the following error 这导致以下错误
> 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'.
Not sure what the issue is here. 不知道这里是什么问题。 if you want to look at the full code i have here is the link Full Code I know there is alot of redundant code I plan to fix it, once i figure this out.
如果您想查看完整的代码,我这里是完整代码的链接,我知道有很多冗余代码,一旦我弄清楚了,我打算修复它。 Any Help is appreciated.
任何帮助表示赞赏。
Try not using hard-coded Documents paths, and don't try to create directories that already exist. 尝试不要使用硬编码的文档路径,也不要尝试创建已经存在的目录。 You also may not want to create the files unless they're missing.
您也可能不想创建文件,除非它们丢失了。
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();
}
}
}
As others have suggested, you may want to move this method out of your main window and into your App
class, then override OnStartup
to call it. 正如其他人所建议的那样,您可能希望将此方法移出主窗口并移至
App
类中,然后重写OnStartup
进行调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.