C# Edit Txt file - c#

I want to add a new line to my txt file.
I tried to write a new line like this:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\text.txt",true))
{
file.WriteLine("SOME TEXT");
}
In this way it goes to the last line and writes, but if I want to write, for example on the fourth line without deleting the old data, how I can do this? How I can define that this string must be written in the forth line?
Thank for atention.

You may use this:
var lines = File.ReadLines(#"C:\text.txt").ToList();
lines.Insert(4, "SOME TEXT");
File.WriteAllLines(#"C:\text.txt", lines);

Related

What is the best way to check if a file contains a key before adding a new line?

I have a CSV file containing the following columns -
Key,Value
First,Line
Second,Line
Third,Line
I want to add a new Key-Value to this file given the key is not already present in the file using C#? What would be the best way to do this? Would I have to traverse line by line and check for the Keys or is there any other better way?
I am not using the CSVHelper package or any other CSV writer.
You could do this:
string path = #"PathToFile.csv";
string Content = string.Empty;
using (StreamReader reader = new StreamReader(path))
{
Content = reader.ReadToEnd();
reader.Close();
}
if (!Content.Contains("YourKey"))
{
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(Content + "\nYourkey,YourValue");
sw.Close();
}
}
Read the file and write all text to a string variable, check the variable if the key exists, if it doesn't then write content back to the file along with your new key. as the file grows it will take longer and longer to search the whole file but it'll work well for a couple thousand lines.

Process each line separately in selected text

I'm trying to select a set of lines and process each line separately in a text document using c# language. How can i get separate lines to process?
I tried these codes and got struck. Can anyone please help me with this?
EnvDTE.DTE dte = MyPackage.MyPackagePackage.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
EnvDTE.TextSelection text = (dte.ActiveDocument.Selection as EnvDTE.TextSelection);
TextSelection interface has got Text property which you can use as string in C#. Further you can split the string to retrieve the lines.
Alternatively TextSelection interface has additional property called TextRanges which has numeric indexers to access each line.
Have a look at this Link form MSDN.
You can use Startpoint and EndPoint for your job.
Also this Link link might be useful to Loop through all the lines from your selection.
If you are reading from a text file this code will help you:
string fileToRead = "D:\\temp.txt"; // Temp.txt is the file to read
if (File.Exists(fileToRead))
{
StreamReader reader = new StreamReader(fileToRead);
do
{
textBox1.Text += reader.ReadLine() + "\r\n"; // Read each line and pass it to the TextBox1
} while (reader.Peek() != -1);
reader.Close(); // Close the file
}

How to edit a css file in ASP.NET using C# to change the website design

I need to make a feature in the website where the admin can change designs of elements like Textbox, header, body and footer and fonts.
I tried
string[] lines= File.ReadAllLines(); method to read all lines and
File.WriteAllLines() to write all the lines after modifying a particular line.
I have adjusted the css to fit each style of the elements in single line for each.
After File.WriteAllLines method, lines sometimes written in a new line, which will affect all other element styles as it depends on line number.
This is what WriteAllLines() does:
using (StreamWriter writer = new StreamWriter(path, false, encoding))
{
foreach (string str in contents)
{
writer.WriteLine(str);
}
}
If any of the strings in 'contents' contains new line ('\n' or '\r\n') then you'll get extra lines written to the file.
Perhaps instead of using WriteAllLines, you could write your own method, that replaces any '\n' or \r\n' in the output before writing them.
e.g.
using (StreamWriter writer = new StreamWriter(path, false, encoding))
{
foreach (string str in contents)
{
writer.WriteLine(str.Replace("\r","").Replace("\n",""));
}
}
In C#:
Somewhat like this
TextboxName.Style.Add("font-size", "14px");

StreamWriter Writes everything on same line

I have a small HttpWebRequest that grabs some text from a online .txt file
After it gets it i want to save it to a .txt file on the computer.
Content of the text is formatet like this:
Line one
Line two
Line four
Line Five
Line ten etc.
But when it saves it ends up like this:
Line oneLine twoLine fourLine FiveLine ten etc.
How may I fix this?
Code is as follows:
HttpWebRequest WebReq3 = (HttpWebRequest)WebRequest.Create("http://test.net/test.txt");
HttpWebResponse WebResp3 = (HttpWebResponse)WebReq3.GetResponse();
System.IO.StreamReader sr3 = new System.IO.StreamReader(WebResp3.GetResponseStream());
System.IO.StreamWriter _WriteResult = new StreamWriter(Application.StartupPath + "\Test.txt");
_WriteResult.Write(sr3.ReadToEnd());
_WriteResult.Close();
sr3.Close();
Read data using ReadLine() and write using WriteLine() instead of ReadToEnd() and WriteToEnd().
Remove this line:
_WriteResult.Write(sr3.ReadToEnd());
And modify your code with this:
string readval = sr3.ReadLine();
while(readval != null)
{
_WriteResult.WriteLine(readval);
readval = sr3.ReadLine();
}
For more details, see the documentation.

How to read the next line in a text document?

I want to know how to read the next line of a text document.
If I click the button, it should open the text document and read the first line.
Then, if I click the "next" button it should read the next line.
How can I do this second button? In C and other languages there are some commands for this..
You need a StreamReader object and then you can invoke the ReadLine method. Don't forget to add the "#" symbol before file path name.
StreamReader sr = new StreamReader(#"C:\\YourPath.txt");
Then on your button clicks you can do:
var nextLine = sr.ReadLine();
The result of each line will be stored in the nextLine variable.
You can use StreamReader.ReadLine
if (myStreamReader.Peek() >= 0)
{
string line = myStreamReader.ReadLine();
}
If you don't want to keep the file open, you can start by reading all lines into memory using File.ReadAllLines
string[] allLines = File.ReadAllLines(path);

Categories

Resources