C# 在C语言中从文本文件中删除一行#
我是C#的新手,我有一个简单的控制台应用程序,带有validateVoters()方法,它接受一个studentID参数,将其与文本文件进行比较,然后返回适当的布尔值。 但是,我希望它删除特定的studentID(如果存在),然后返回true,但没有通用的从文件中删除方法,因此我在这里使用了一个成员推荐的方法: 给我一个双星号的方法错误**:C# 在C语言中从文本文件中删除一行#,c#,file-io,C#,File Io,我是C#的新手,我有一个简单的控制台应用程序,带有validateVoters()方法,它接受一个studentID参数,将其与文本文件进行比较,然后返回适当的布尔值。 但是,我希望它删除特定的studentID(如果存在),然后返回true,但没有通用的从文件中删除方法,因此我在这里使用了一个成员推荐的方法: 给我一个双星号的方法错误**: 错误2 名称“RemoveUnnecessaryLine”在当前上下文c:\Users\Hlogyatau\Documents\Visual Studio
错误2
名称“RemoveUnnecessaryLine”在当前上下文c:\Users\Hlogyatau\Documents\Visual Studio 2010\Projects\Ijoo\Ijoo\Program.cs 28 43 Ijoo中不存在
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace SRCVotingSystem
{
public class Program
{
public bool validateVoter(String cisNo)
{
bool found = false;
try
{
string[] ID = System.IO.File.ReadAllLines(@"C:\Users\Hlogoyatau\Pictures\votersRoll.txt");
foreach (string line in ID)
{
//compares it against text file contents
if (cisNo == line)
{
string[] allLines= File.ReadAllLines("votersRoll.txt");
string[] newIDs= **RemoveUnnecessaryLine**(allLines);
File.WriteAllLines("votersRoll.txt", newIDs);
found = true;
}
}
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
return found;
}
public static void Main()
{
Program vv = new Program();
Console.WriteLine(vv.validateVoter("cis11-005"));
}
}
}
试试这个:
public bool validateVoter(String cisNo)
{
bool found = false;
try
{
string[] ID = System.IO.File.ReadAllLines(@"C:\Users\Hlogoyatau\Pictures\votersRoll.txt");
for (int i = 0; i < ID.Length; i++)
{
string line = ID[i];
//compares it against text file contents
if (cisNo == line)
{
//Shift remaining lines up, overwriting current line
for (int j = i; j < ID.Length - 1; j++)
{
ID[j] = ID[j+1];
}
//Set last line to empty string
ID[ID.Length - 1] = "";
//Write file back to disk
System.IO.File.WriteAllLines(@"C:\Users\Hlogoyatau\Pictures\votersRoll.txt", ID);
found = true;
//Exit loop after something is found
break;
}
}
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
return found;
}
public bool validateVoter(字符串cisNo)
{
bool-found=false;
尝试
{
string[]ID=System.IO.File.ReadAllLines(@“C:\Users\hlogayatau\Pictures\votersRoll.txt”);
for(int i=0;i
它将读取文件,当找到匹配项时,它将剩余的行向上移动一行。最后一行将被清除,然后文件被写回磁盘。如果不希望最后一行为空,则可以调整数组大小(请参见)。尝试使用LINQ
public void validateVoter(String cisNo)
{
var newIDs = System.IO.File.ReadAllLines(@"C:\Users\Hlogoyatau\Pictures\votersRoll.txt").Where(l => l != cisNo);
File.WriteAllLines(@"C:\Users\Hlogoyatau\Pictures\votersRoll.txt", newIDs);
}
因为它实际上并不存在。。。这是你自己写的。编一个函数名并不会神奇地创造出一个你想要它做的函数。谢谢:(-1:@EdS的评论很好,但不足以让这个问题变得好。你的帖子并没有显示出你自己努力寻找答案的效果——也值得感谢你有一个好的描述性函数名。
/* sample data in text.tx
ID 1 asdfsdaf
ID 2 asdfdsafasdfsadf
ID 3 lkjasdfjsdf
*/
private static void Main(string[] args)
{
var id = 2;
var lines = File.ReadAllLines("C:\\temp\\text.txt");
var remaining = lines.Where(x => !x.Contains(id.ToString())).ToArray();
File.WriteAllLines("C:\\temp\\out.txt", remaining);
}