首页 > 解决方案 > 在 C# 中强制 .txt 文件扩展名

问题描述

我编写了一个用于读取用户用户代码的函数。然后,如果创建的文件存在于数据库中,则将该文件读入控制台——如果它不存在,则创建该文件。

但是,.txt它不是创建应有的文件,而是创建一个.FILE. 此外,当代码将文件读入控制台时,它只输出AGE变量而不是NAME变量。

我做错了什么?以及如何强制它成为一个.txt文件?这是我的.cs文件:

public class Users
{
    static string age;
    static string name;
    static string user = Exercise4.personalpword;
    static string somePath = @"C:\users\jmanthony\desktop\infolder";
    static string path = Path.Combine(somePath, user);


    public static void Fn()
    {
        Console.WriteLine("What is your age?");
        age = Console.ReadLine();
        Console.WriteLine("What is your name?");
        age = Console.ReadLine();
        using (StreamWriter sw = File.CreateText(path))
        {
            sw.WriteLine(age);
            sw.WriteLine(name);
        }
    }
    public static void Conditions()
    {
        if (File.Exists(path))
        {
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }

        else
        {
            Console.WriteLine("ERROR: File does not exist, please create.");
            Fn();
        }

    }
    public static void Josh()
    {
        Conditions();
    }

    public static void User1()
    {
        Conditions();
    }
}

标签: c#

解决方案


您的代码从不指定您要创建文本文件。您可以使用Path.ChangeExtension.NET 库中的方法执行此操作:

string textFile = System.IO.Path.ChangeExtension(user, "txt");

然后在 Path.Combine 调用中使用该变量:

Path.Combine(somePath, textFile)

您还错误地重用了您的年龄变量,从而覆盖了用户输入的年龄。这是一个简单的更正:更改第二个

age = Console.ReadLine();

name = Console.ReadLine();

推荐阅读