无法在C#项目中的AppData中创建文件夹

时间:2016-11-11 20:07:22

标签: c#

这是一个我认识到的足够简单的主题,但我无法在我正在处理的应用程序中创建一个文件夹。我在诊断问题时遇到了问题。应用程序可以正常运行代码,但不会创建文件和文件夹。文件夹和设置文件的位置将在AppData \ Roaming中。这是我正在使用的代码,我认为这是正确的:

    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");
    }

最困扰我的是我尝试了几种方法来实现这一点,我在SO上的几个帖子帖子中找到了。他们都没有按预期破坏应用程序,但没有任何反应。好像代码被完全跳过或忽略了。如果有人想知道,我已经将System.IO引入了命名空间。该应用程序是一个WinForms应用程序。

我是一个完整的C#菜鸟,基本上是编程,但这看起来很简单。非常感谢任何帮助...

编辑:这是代码的第一部分。这直接在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();
        }

2 个答案:

答案 0 :(得分:1)

如果它永远不会被击中,那么你就会错过订阅该事件的行。

Load += new EventHandler(TestForm_Load);

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

Properties Dialog

您可能没有订阅表单的加载事件。假设类名是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");
    }
}

答案 1 :(得分: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);
}

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