2016-11-11 63 views
0

这是一个足够简单的主题,但我无法在正在处理的应用程序中创建文件夹。我在诊断问题时遇到了问题。该应用运行良好的代码,但没有创建文件和文件夹。文件夹和设置文件的位置将位于AppData \ Roaming中。这里是我使用的代码,我相信这是正确的:这是最困扰我在C#项目的AppData中创建文件夹时遇到的问题

private void TestForm_Load(object sender, EventArgs e) 
    { 
     string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); 
     if (!Directory.Exists(path + "\\TestFolder")) 
      Directory.CreateDirectory(path + "\\TestFolder"); 
     if (!File.Exists(path + "\\TestFolder\\settings.xml")) 
      File.Create(path + "\\TestFolder\\settings.xml"); 
    } 

的事情是,我尝试了好几种方法可以做到这一点,我在这里有这么几种线程发现帖子。没有人按预期打破应用程序,但没有任何反应。就好像代码被完全跳过或忽略一样。如果有人想知道,我已经将System.IO引入命名空间。该应用程序是一个WinForms应用程序。

我是C#的完全noob,基本上是编程,但这似乎很简单。非常感谢您的帮助...

编辑:这是代码的第一部分。这直接在Form.cs(TestForm.cs)文件的前面。也许这将帮助:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 

namespace WindowsFormsApplication1 
{ 
    public partial class TestForm : Form 
    { 
     public TestForm() 
     { 
      InitializeComponent(); 
     } 
+0

确保事件处理函数被调用。在第一行设置一个断点并在调试模式下运行你的应用程序。也许事件处理程序没有附加到TestForm? –

+0

道歉,试图在这里添加一些代码... –

+0

请参阅http://stackoverflow.com/a/9847686/1260204。您可能没有订阅OnLoad事件。 – Igor

回答

1

如果这是从来没有被击中你缺少的订阅了该事件的线。

Load += new EventHandler(TestForm_Load); 

您还可以订阅窗体设计器中的加载事件。使用F4查看属性对话框,单击表单标题栏,然后导航到属性中的事件(闪电)。活动的名称是Load

Properties Dialog


您可能没有订阅窗体的Load事件。假设类名是TestForm,它应该与此类似,附加到事件是构造函数中的第二个loc。

public partial class TestForm : Form { 

    public TestForm() 
    { 
     InitializeComponent(); 
     Load += new EventHandler(TestForm_Load); // !! Add this line !! 
    } 

    private void TestForm_Load(object sender, EventArgs e) 
    { 
     string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); 
     if (!Directory.Exists(path + "\\TestFolder")) 
      Directory.CreateDirectory(path + "\\TestFolder"); 
     if (!File.Exists(path + "\\TestFolder\\settings.xml")) 
      File.Create(path + "\\TestFolder\\settings.xml"); 
    } 
} 
+0

Thankyou。这正是缺少的。这一切都很清楚,现在哈哈... :) –

+0

@BoMcCullough - 很高兴为你工作。请考虑接受答案(请参阅[如何接受答案](http://meta.stackexchange.com/a/5235))。 – Igor

0

只是编码风格的说明 - 我切换到使用构建“安全”路径Path.Combine方法。像这样:

private void TestForm_Load(object sender, EventArgs e) 
{ 
    string directory = Path.Combine(Environment.SpecialFolder.ApplicationData, "TestFolder"); 
    if (!Directory.Exists(directory)) 
     Directory.CreateDirectory(directory); 

    string file = Path.Combine(directory, "settings.xml"); 
    if (!File.Exists(file)) 
     File.Create(file); 
} 

谢谢,我希望我说对了......

相关问题