I am using this code so far - it writes the file but doesn't remove the line specified.. any help would be nice...
if (textBox1.Text == "")
{
MessageBox.Show("Please select a file");
}
else
{
string line = null;
StringBuilder sb = new StringBuilder();
string lineDelete = "hi";
// Read the file and display it line by line.
using (System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text)){
using (System.IO.StreamWriter writer = new System.IO.StreamWriter("C:\\test3.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (String.Compare (line, lineDelete) == 0)
continue;
writer.WriteLine(line);
}
MessageBox.Show("Formatting Complete");
// Suspend the screen.
}
}
"It doesn't remove the line specified" is somewhat misleading, isn't it? You are writing lines from file1 to file2, lines which are "hi" will be omitted. So you are ignoring, not deleting those lines. Is that what you want? Also, note that C# is case sensitive and that there also might be special characters which you can't see directly like white-spaces.
So you could use Trim to remove white-spaces from the start and end of the line and you can use String.Equals to compare case-insensitive:
while ((line = file.ReadLine()) != null)
{
line = line.Trim();
if(line.Equals(lineDelete, StringComparison.CurrentCultureIgnoreCase));
continue;
else
writer.WriteLine(line);
}
Related
I'm trying to remove lines that are in between two different lines. Currently, I have:
string s = "";
String path = #"C:\TextFile";
StreamWriter sw = new StreamWriter(path, true);
StreamReader sr = new StreamReader(path, true);
s = sr.ReadLine();
if (s=="#Start")
{
while (s != "#End")
{
sw.WriteLine(s);
//need something here to overwrite existing data with s not just add s
}
}
sr.Close();
sw.Close();
The content of my text file looks like this:
#Start
facebook.com
google.com
youtube.com
#End
I tried to follow Efficient way to delete a line from a text file however it deletes any file containing a certain character, whereas there are other lines outside of the range containing .com that I don't want to remove
I want to delete all the contents in between start and end so after the method runs the remains of the text file is
#Start
#End
You have two problems:
You're only reading the first line, and then you're using that one value everywhere. Clearly if s == "#Start", it can't also satisfy the condition s == "#End", etc.
Even if you were reading each line, you expect that after #End there will be no more data - you don't loop through the rest of the lines, you just stop writing. Based on your question, I think you want to write all lines from the file and only change those between #Start and #End.
-
Perhaps a constant loop as below would be better?:
string s;
bool inRewriteBlock = false;
while ((s = sr.ReadLine()) != null)
{
if (s == "#Start")
{
inRewriteBlock = true;
}
else if (s == "#End")
{
inRewriteBlock = false;
}
else if (inRewriteBlock)
{
sw.WriteLine(s);
//need something here to overwrite existing data with s not just add s
}
else
{
sw.WriteLine(s);
}
}
By default, the code will output every line it reads verbatim. However, if it reads #Start it will enter a special mode (inRewriteBlock == true) where you can rewrite those lines however you want. Once it reaches #End it will transition back into the default mode (inRewriteBlock == false).
You can simply do this: (This assumes file can be stored in memory)
string path = #"C:\\Users\\test\\Desktop\\Test.txt";
List<string> fileData = File.ReadAllLines(path).ToList();
// File.ReadAllLines(path).ToList().Select(y => y.Trim()).ToArray().ToList(); will remove all trailing/preceding spaces in data
int startsWith = fileData.IndexOf("#Start");
int endsWith = fileData.IndexOf("#End");
if(startsWith != -1 && endsWith != -1)
fileData.RemoveRange(startsWith+1, endsWith-1);
File.WriteAllLines("C:\\Test\\Test1.txt", fileData.ToArray());
It doesnt account for special scenarios like startsWith is at the end of the file with no endswith.
You should check and rewrite every thing between #Start and #End instead of file is start with "#Start" only.
You can try this:
//Read all text lines first
string[] readText = File.ReadAllLines(path);
//Open the text file to write
var oStream = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.Read);
StreamWriter sw = new System.IO.StreamWriter(oStream);
bool inRewriteBlock = false;
foreach (var s in readText)
{
if (s.Trim() == "#Start")
{
inRewriteBlock = true;
sw.WriteLine(s);
}
else if (s.Trim() == "#End")
{
inRewriteBlock = false;
sw.WriteLine(s);
}
else if (inRewriteBlock)
{
//REWRITE DATA HERE (IN THIS CASE IS DELETE LINE THEN DO NOTHING)
}
else
{
sw.WriteLine(s);
}
}
sw.Close();
I need to remove specific line in txt file which means i need to read and rewrite the whole file leaving out the specific line , i tried but i get unhandled-exeption (The process cannot access the file because it is being used by another procces).
All i used in the processes suspicious was :
1 . this line
IEnumerable<string> text = System.IO.File.ReadAllLines(#"C:\TreeView.txt");
which i used to get all lines into "string"
and this part of the method which supposed to delete specific line from txt
string line = null;
string filePath = #"c:\TreeView.txt";
using (StreamReader reader = new StreamReader(filePath, true))
{
using (StreamWriter sw = new StreamWriter(filePath))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line, obj) == 0)
continue;
sw.WriteLine(line);
}
}
}
The problem is in the second part where you are opening the file for reading and then trying to open it for writing. You could simply do something like this:
var text = System.IO.File.ReadAllLines(#"C:\TreeView.txt");
System.IO.File.WriteAllLines(#"C:\TreeView.txt",
text.Where(x => String.Compare(line, obj) != 0));
i have following code i want this line and next 2 below lines how do this any idea. please help,i want last number please see text below.
static void Main()
{
int counter = 0; string line;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
sb.AppendLine(line.ToString());
}
}
}
Console.WriteLine(sb.ToString());
Console.ReadKey();
}
***** INCOMING CALL: 25/04/2016 - 11:45 *****
NAME: Test
NUMBER: (425) 555-1212
***** INCOMING CALL: 25/04/2016 - 11:45 *****
NAME: Test2
NUMBER: (425) 544-1213
Just call file.ReadLine two more times, but it is important to check if the returned string is null because you could reach an unexpected end of file and your code is no more protected by the check in the while condition
...
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
}
}
}
If you want to get just the last three lines (assuming that your file is well formatted) then you could add a reset of the StringBuilder inside the loop
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
// This will remove the previous data and keep
// just the last three lines.....
sb.Length = 0;
sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
line = file.ReadLine();
if(line != null) sb.AppendLine(line);
}
}
}
In alternative, but I am not sure if this is a good idea from a performance point of view (in particular if we are talking of a large file), we could use linq in this way
string result = string.Join(Environment.NewLine,
File.ReadLines(#"E:\file\log.txt").Reverse().Take(3));
static void Main()
{
int counter = 0; string line;
List<string> ss = new List<string>();
using (System.IO.StreamReader file = new System.IO.StreamReader(#"E:\file\log.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(DateTime.Now.Date.ToShortDateString()))
{
ss.Add(line);
line = file.ReadLine();
if (line != null)
ss.Add(line);
line = file.ReadLine();
if (line != null)
ss.Add(line);
}
}
}
var item = ss.LastOrDefault();
string number = item.Substring(0, 24).Replace("NUMBER:", "").Trim();
Console.WriteLine(number);
Console.ReadKey();
}
In C# why output of this 2 code is different from each other ?
StreamReader test = new StreamReader(#"C:\a.txt");
while (test.ReadLine() != null)
{
Console.WriteLine(test.ReadLine());
}
And this code :
StreamReader test = new StreamReader(#"C:\a.txt");
string line = "";
while ((line = test.ReadLine()) != null)
{
Console.WriteLine(line);
}
Each time you call test.ReadLine() you read one new line, so the first code skippes a half of them.
In your first example, use this code instead:
while(!test.EndOfStream)
{
Console.WriteLine(test.ReadLine());
}
Both the code works same with little magic ,becuase of the reason:
test.ReadLine():
return: The next line from the input stream, or null if the end of the input stream is reached.
// So,Let's say your a.txt contain the following cases:
case 1:"Hello World"
while (test.ReadLine() != null)
{
Console.WriteLine("HI" + test.ReadLine());
}
// since,we have only one line ,so next line is null and finally it reached the EOD.
case 2:"Hello World"
"I am a coder"
while (test.ReadLine() != null)
{
Console.WriteLine("HI" + test.ReadLine());
}
// since,we have two line so ,next line is "I am a coder".
//It returns:Hi I am a coder.
// And in the below code we are reading and assigning to string variable
StreamReader test1 = new StreamReader(#"D:\a.txt");
string line = "";
while ((line = test1.ReadLine()) != null)
{
Console.WriteLine(line);
}
I need to delete an exact line from a text file but I cannot for the life of me workout how to go about doing this.
Any suggestions or examples would be greatly appreciated?
Related Questions
Efficient way to delete a line from a text file (C#)
If the line you want to delete is based on the content of the line:
string line = null;
string line_to_delete = "the line i want to delete";
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
if (String.Compare(line, line_to_delete) == 0)
continue;
writer.WriteLine(line);
}
}
}
Or if it is based on line number:
string line = null;
int line_number = 0;
int line_to_delete = 12;
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
line_number++;
if (line_number == line_to_delete)
continue;
writer.WriteLine(line);
}
}
}
The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.
There is no generic delete-a-line-from-file function, as far as I know.
One way to do it if the file is not very big is to load all the lines into an array:
string[] lines = File.ReadAllLines("filename.txt");
string[] newLines = RemoveUnnecessaryLine(lines);
File.WriteAllLines("filename.txt", newLines);
Hope this simple and short code will help.
List linesList = File.ReadAllLines("myFile.txt").ToList();
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());
OR use this
public void DeleteLinesFromFile(string strLineToDelete)
{
string strFilePath = "Provide the path of the text file";
string strSearchText = strLineToDelete;
string strOldText;
string n = "";
StreamReader sr = File.OpenText(strFilePath);
while ((strOldText = sr.ReadLine()) != null)
{
if (!strOldText.Contains(strSearchText))
{
n += strOldText + Environment.NewLine;
}
}
sr.Close();
File.WriteAllText(strFilePath, n);
}
You can actually use C# generics for this to make it real easy:
var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
file.RemoveAt(12);
File.WriteAllLines("C:\\path", file.ToArray());
This can be done in three steps:
// 1. Read the content of the file
string[] readText = File.ReadAllLines(path);
// 2. Empty the file
File.WriteAllText(path, String.Empty);
// 3. Fill up again, but without the deleted line
using (StreamWriter writer = new StreamWriter(path))
{
foreach (string s in readText)
{
if (!s.Equals(lineToBeRemoved))
{
writer.WriteLine(s);
}
}
}
Read and remember each line
Identify the one you want to get rid
of
Forget that one
Write the rest back over the top of
the file
I cared about the file's original end line characters ("\n" or "\r\n") and wanted to maintain them in the output file (not overwrite them with what ever the current environment's char(s) are like the other answers appear to do). So I wrote my own method to read a line without removing the end line chars then used it in my DeleteLines method (I wanted the option to delete multiple lines, hence the use of a collection of line numbers to delete).
DeleteLines was implemented as a FileInfo extension and ReadLineKeepNewLineChars a StreamReader extension (but obviously you don't have to keep it that way).
public static class FileInfoExtensions
{
public static FileInfo DeleteLines(this FileInfo source, ICollection<int> lineNumbers, string targetFilePath)
{
var lineCount = 1;
using (var streamReader = new StreamReader(source.FullName))
{
using (var streamWriter = new StreamWriter(targetFilePath))
{
string line;
while ((line = streamReader.ReadLineKeepNewLineChars()) != null)
{
if (!lineNumbers.Contains(lineCount))
{
streamWriter.Write(line);
}
lineCount++;
}
}
}
return new FileInfo(targetFilePath);
}
}
public static class StreamReaderExtensions
{
private const char EndOfFile = '\uffff';
/// <summary>
/// Reads a line, similar to ReadLine method, but keeps any
/// new line characters (e.g. "\r\n" or "\n").
/// </summary>
public static string ReadLineKeepNewLineChars(this StreamReader source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
char ch = (char)source.Read();
if (ch == EndOfFile)
return null;
var sb = new StringBuilder();
while (ch != EndOfFile)
{
sb.Append(ch);
if (ch == '\n')
break;
ch = (char)source.Read();
}
return sb.ToString();
}
}
Are you on a Unix operating system?
You can do this with the "sed" stream editor. Read the man page for "sed"
What?
Use file open, seek position then stream erase line using null.
Gotch it? Simple,stream,no array that eat memory,fast.
This work on vb.. Example search line culture=id where culture are namevalue and id are value and we want to change it to culture=en
Fileopen(1, "text.ini")
dim line as string
dim currentpos as long
while true
line = lineinput(1)
dim namevalue() as string = split(line, "=")
if namevalue(0) = "line name value that i want to edit" then
currentpos = seek(1)
fileclose()
dim fs as filestream("test.ini", filemode.open)
dim sw as streamwriter(fs)
fs.seek(currentpos, seekorigin.begin)
sw.write(null)
sw.write(namevalue + "=" + newvalue)
sw.close()
fs.close()
exit while
end if
msgbox("org ternate jua bisa, no line found")
end while
that's all..use #d