c# - 在 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();
}
}
解决方案
您的代码从不指定您要创建文本文件。您可以使用Path.ChangeExtension
.NET 库中的方法执行此操作:
string textFile = System.IO.Path.ChangeExtension(user, "txt");
然后在 Path.Combine 调用中使用该变量:
Path.Combine(somePath, textFile)
您还错误地重用了您的年龄变量,从而覆盖了用户输入的年龄。这是一个简单的更正:更改第二个
age = Console.ReadLine();
至
name = Console.ReadLine();
推荐阅读
- flutter - 字符串未使用 changeNotifierProvider 更新
- spring-boot - SpringData MongoDb Repository FindObject List Field by List
- python - 如何使用 matplotlib 绘制复杂的条形图——具有多行条形的多个子图?
- r - R中的数值求解器(近似十进制解)
- python - 如何使用熊猫每 15 分钟填充一次
- python-3.x - 在后台运行的 Python 自动化项目
- powershell - 如何在 powershell("user:mary@contoso.com:rwx,default:user:mary@contoso.com:rwx") 中参数化两个值的字符串
- r - 如何随时间绘制二进制数据(ggplot)
- standards - 我如何知道正在使用哪些 RFC?
- c - C GZIP 得到不正确的结果