[英]Writing to a sorted text file
I am unsure of what I am doing wrong here. 我不确定在这里我做错了什么。 It compiles and runs, and acts ok, but it is not writing the line into the text file.
它可以编译并运行,并且可以正常运行,但是没有将行写入文本文件。 I have my FileStream and read on MSDN to try and figure this out on my own.
我有FileStream并在MSDN上阅读以尝试自己解决这个问题。 When I did get something to work, it overwrote the entire file with what I put into it.
当我确实需要工作时,它会将我放入的文件覆盖了整个文件。 So I am hoping maybe a programmer who has done this for more than 4 months (such as me) can explain.
所以,我希望,也许谁做这个了4个多月(比如我),程序员可以解释。 Here is a piece of my code that I think is relevant.
这是我认为相关的一段代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication33
{
class Program
{
static void Main(string[] args)
{
FileStream FireBall = new FileStream("Students.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(FireBall);
string inValue;
string[] values;
double GPA;
double total = 0;
double counter = 0;
double count = 0;
double counti = 0;
double counterr = 0;
List<string> Anderson = new List<string>(); //Anderson
List<string> gpa = new List<string>(); //GPA
List<string> noemail = new List<string>(); // email
List<string> lines = new List<string>();
string newLastName = "'Constant";
string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 'mdconstant@mail.usi.edu 4.000000 )";
string line;
string lastName;
bool insertionPointFound = false;
for (int i = 0; i < lines.Count && !insertionPointFound; i++)
{
line = lines[i];
if (line.StartsWith("(LIST (LIST "))
{
values = line.Split(" ".ToCharArray());
lastName = values[2];
if (newLastName.CompareTo(lastName) < 0)
{
lines.Insert(i, newRecord);
insertionPointFound = true;
}
}
}
if (!insertionPointFound)
{
lines.Add(newRecord);
}
You don't do any writing here. 你在这里不写任何东西。 Note that you are using
FileAccess.Read
in 请注意,您正在使用
FileAccess.Read
in
FileStream FireBall = new FileStream("Students.txt", FileMode.Open, FileAccess.Read);
It should be replaced with FileAccess.ReadWrite
应该将其替换为
FileAccess.ReadWrite
You can use StreamWrite
to write to the file. 您可以使用
StreamWrite
写入文件。 And you can read and write easily with File.ReadAllText
and File.WriteAllText
而且,您可以使用
File.ReadAllText
和File.WriteAllText
轻松进行File.WriteAllText
What I don't see is any code that writes to the file itself. 我看不到任何写入文件本身的代码。 If you are reading the contents of the file into the
lines
List
, writing to that list is not the same as writing to the actual file. 如果要将文件的内容读到
List
lines
,则写入该列表与写入实际文件不同。
So you need to explicitly write to the file, with something like a StreamWriter
. 因此,您需要使用
StreamWriter
类的方法显式写入文件。 See here: http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx 看到这里: http : //msdn.microsoft.com/en-us/library/6ka1wd3w.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.