C#WPF - 尝试在应用程序启动时创建文件时出错

问题描述:

我是Visual Studio的新手,我正在尝试创建一个.ahk文件的应用程序。我的问题是,当应用程序启动时,我需要它创建几个文件/文件夹。要做到这一点,我添加以下代码C#WPF - 尝试在应用程序启动时创建文件时出错

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 我知道有很多冗余代码我打算修复它,一旦我找到了这一点。任何帮助表示赞赏。

+1

围绕您在构造函数中的代码进行try/catch,然后将有关该异常的信息添加到您的问题中。没有这些例外情况,很难说出问题所在。 – user469104 2014-11-03 16:42:24

+3

你的错误是在xaml中,而不是在发布的代码中。 – paqogomez 2014-11-03 16:45:30

+0

xmlns:x =“http://schemas.microsoft.com/winfx/2006/xaml” - 这是来自.xaml的第3行 – 2014-11-03 16:47:42

尝试不使用硬编码的文档路径,并且不要尝试创建已经存在的目录。除非缺失,否则您也可能不想创建这些文件。

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调用它。