设置文件的路径

时间:2016-10-18 01:46:22

标签: c# path

我想使用此方法https://stackoverflow.com/a/11967357/5425608来创建文件。但是,var只能在方法https://stackoverflow.com/a/5337470/5425608中使用。如何将路径的名称转换为类变量,以便由类中的其他方法访问。

例如,在下面的代码中," labelPath"不在setPaths()方法的var labelPath范围内。我还有其他方法使用" path"和" objectPath"这些变量不在这些方法的范围内。

非常感谢任何帮助。

    public Form2()
    {
        InitializeComponent();
        setPaths();
        current = this;
        instantiateNumUpDown();
        System.IO.File.WriteAllText(labelPath, " ");

    }

    public static void setPaths()
    {
        var systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

        var path = Path.Combine(systemPath, "TextDynamic.txt");
        var labelPath = Path.Combine(systemPath, "currentLabel.txt");
        var objectPath = Path.Combine(systemPath, "object.txt");

    }

3 个答案:

答案 0 :(得分:0)

你不能这样做,因为var本身不是一个类型,它在赋值的右边获得值的类型。

相反,您可以将变量类型定义为字符串并在类

下声明
public class A
{
        private static string systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
        private string path = Path.Combine(systemPath, "TextDynamic.txt");
        private string labelPath = Path.Combine(systemPath, "currentLabel.txt");
        private string objectPath = Path.Combine(systemPath, "object.txt");
}

答案 1 :(得分:0)

试试这个:

public class Form2
{
    private static string labelPath;
    private static string objectPath;
    private static string path;
    public Form2()
    {
        InitializeComponent();
        setPaths();
        current = this;
        instantiateNumUpDown();
        System.IO.File.WriteAllText(Form2.labelPath, " ");

    }

    public static void setPaths()
    {
        var systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

        path = Path.Combine(systemPath, "TextDynamic.txt");
        labelPath = Path.Combine(systemPath, "currentLabel.txt");
        objectPath = Path.Combine(systemPath, "object.txt");

    }    
}

答案 2 :(得分:0)

因为您的变量“path”“labelPath”“objectPath”全部来自From2的构造方法,要修复它,您应该这样做:

public Form2()
{
    InitializeComponent();

    string path = string.empty;
    string labelPath = string.empty;
    string objectPath = string.empty;

    setPaths(ref path, ref labelPath, ref objectPath);

    current = this;
    instantiateNumUpDown();
    System.IO.File.WriteAllText(labelPath, " ");

}

public static void setPaths(ref string path, ref string labelPath, ref string objectPath)
{
    var systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

    path = Path.Combine(systemPath, "TextDynamic.txt");
    labelPath = Path.Combine(systemPath, "currentLabel.txt");
    objectPath = Path.Combine(systemPath, "object.txt");

}