【发布时间】:2015-09-16 20:25:32
【问题描述】:
using System;
namespace CAT
{
class MainClass
{
public static void Main (string[] args)
{
string path = @"E:\CAT\Name.txt";
if (!System.IO.File.Exists(path))
{
System.IO.File.Create(path);
System.IO.TextWriter tw = new System.IO.StreamWriter(path);
tw.WriteLine("File Created!");
tw.Close();
} else if (System.IO.File.Exists(path)){
System.IO.TextWriter tw = new System.IO.StreamWriter(path, true);
tw.WriteLine("New Boot.");
tw.Close();
}
Console.WriteLine("Directory System - Copyright 2016 xxxxCo.");
Console.WriteLine("What is your surname?");
string Surname = Console.ReadLine();
System.IO.TextWriter fileEnter = new System.IO.StreamWriter(path);
fileEnter.WriteLine(Surname);
Console.WriteLine ("What is your first name?");
string fn = Console.ReadLine ();
fileEnter.WriteLine(fn);
Console.WriteLine ("Hello " + fn + " " + Surname);
Console.Read();
Console.Clear();
Console.WriteLine("Directory System - Copyright 2016 xxxxCo.");
Console.WriteLine ("Year?");
string year = Console.ReadLine();
// New file created for year and meta data
string yearpath = @"E:\CAT\Year.txt";
if (!System.IO.File.Exists(yearpath))
{
System.IO.File.Create(yearpath);
System.IO.TextWriter tw = new System.IO.StreamWriter(yearpath);
tw.WriteLine("File Created!");
tw.Close();
}
else if (System.IO.File.Exists(yearpath))
{
System.IO.TextWriter tw = new System.IO.StreamWriter(yearpath, true);
tw.WriteLine("New Boot.");
tw.Close();
}
// new text writer created for year data
System.IO.TextWriter fileEnterYear = new System.IO.StreamWriter(yearpath);
fileEnterYear.WriteLine(year + " " + fn.Substring(0, 1) + Surname.Substring(0, 1));
Console.Read();
}
}
请原谅我糟糕的组织,因为我刚刚下载了 Xamarin Studio,所以我把它作为一个测试程序来做。每个文件都是在它们各自的位置创建的,但随后都不会被写入。请帮我解决这个问题,因为我看不到我的错误是什么。 非常感谢
【问题讨论】:
-
你熟悉使用调试器吗..为什么人们想编写代码但不能使用他们可以使用的工具来逐步执行他们自己的代码..之前关闭文件放
tw.Flush()然后关闭文件也.. 并且不调用Dispose直接将您的StreamWriter 代码包装在using周围,例如using(StreamWriter tw = new StreamWriter(File.OpenWrite(yearpath)) -
如果您调试代码并看到它实际上正在执行写入,请尝试在发出关闭之前使用 Flush。见:stackoverflow.com/questions/7376956/…
-
您是否希望将所有行都写入一个文件。我会快速重构您的混乱并使其更具可读性,请给我 2 分钟
-
File.WriteAllText 和 File.AppendAllText 会起作用吗?不需要流,WriteAllX 会自动创建文件。
-
@TriggSharp 我修复了您的代码并使其正常运行,如果您有任何其他问题,请告诉我,谢谢
标签: c# visual-studio c#-4.0 xamarin