Change a line in a file containing a specific String in C# - c#

ive got a problem: i want to find a line containing a certain string, but i only know how to replace the string in the file or all the lines, i know the command "string.Contains", but it doesnt seem to work properly as i use it: i tried to use "if (data.contains(string))", but then it still changes all the lines to that string. heres my code:
private void button1_Click(object sender, EventArgs e)
{
string replaceText = "peter";
string withText = "Gilbert";
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(#"C:\Users\G\Documents\test.txt"))
{
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(#"C:\Users\G\Documents\test.txt" + ".tmp"))
{
while (!streamReader.EndOfStream)
{
string data = streamReader.ReadLine();
data = data.Replace(replaceText, withText);
streamWriter.WriteLine(data);
}
}
}
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(#"C:\Users\G\Documents\test.txt" + ".tmp"))
{
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(#"C:\Users\G\Documents\test.txt"))
{
while (!streamReader.EndOfStream)
{
string data = streamReader.ReadLine();
data = data.Replace(replaceText, withText);
streamWriter.WriteLine(data);
}
}
}
}
}

Try this:
FileStream stream = File.Open("file", FileMode.Open);
StreamReader rdr = new StreamReader(rdr);
String[] flines = rdr.ReadToEnd().Split(new String[]{"\r\n"}, StringSplitOptions.None);
rdr.Close();
stream = File.Create("file");
StreamWriter wtr = new StreamWriter(stream);
foreach(String str in flines)
{
wtr.WriteLine(str.Replace(replaceTxt, newText));
}
wtr.Close();
Of course you could put logic in the loop the either change or not change the string written based on whatever criterion you like.

Related

How can i impove my code?

Because I have no experience with sockets and I don't know how to make one, I have this code:
public void getGameInfo()
{
string content;
do
{
WebClient client = new WebClient();
client.DownloadFile(fileadress, filename);
client.Dispose();
StreamReader reader = new StreamReader(filename);
content = reader.ReadToEnd();
reader.Close();
} while (content == "");
File.Delete(filename);
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = zeilen[0];
gameInfo = new string[line.Length-1];
Array.Copy(lines, 1, gameInfo, 0, lines.Length-1);
}
It connects to a Apache server with a .txt file and reads it. But if too many Programms (three) uses the code, it will throw a WebException.
So is there a way to improve this, or a guide to make a socket for this?
Edit 1:
And what if I want to write to the file like this function?
public void setSpielInfo(int line, string input)
{
WebClient client = new WebClient();
string content;
do
{
client.DownloadFile(gameadress, filename);
StreamReader reader = new StreamReader(filename);
content = reader.ReadToEnd();
reader.Close();
} while (content == "");
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
lines[zeile+1] = input;
byte[] bytearray = Encoding.ASCII.GetBytes(string.Join(Environment.NewLine, lines)); // I've read that byte arrays are faster than string arrays
FileStream writer = new FileStream(filename, FileMode.Truncate);
writer.Write(bytearray, 0, bytearray.Length);
writer.Close();
client.UploadFile(ftpAdress, filename);
client.Dispose();
File.Delete(filename);
}
You want to read string, right? So why do you download file?
string content;
// Do not dispose explicitly, wrap into using instead
using (WebClient client = new WebClient()) {
content = client.DownloadString(fileadress);
}
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault(); // 1st line
gameInfo = lines.Skip(1).ToArray(); // all the others
You can further shorten the code into
using (WebClient client = new WebClient()) {
var lines = client
.DownloadString(fileadress)
.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault();
gameInfo = lines.Skip(1).ToArray();
}
Edit: again, what do you actually want to perform: download a string, write file, upload the file:
string content;
// Do not dispose explicitly, wrap into using instead
using (WebClient client = new WebClient()) {
// Download string (text)
content = client.DownloadString(fileadress);
// Write the text to file (override existing if it is)
File.WriteAllText(filename, content);
// Upload file
// think on uploading the string - client.UploadString(ftpAdress, content);
client.UploadFile(ftpAdress, filename);
}
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault(); // 1st line
gameInfo = lines.Skip(1).ToArray(); // all the others
As the further improvent think on working with string not files:
using (WebClient client = new WebClient()) {
// Download string (text)
content = client.DownloadString(fileadress);
client.UploadString(ftpAdress, content);
}

C# how to read 2 files using Stream and response both as 1

I need to read 2 files and somehow combine them and response them both as 1.
I don't want to create a new file containing both files text.
This is my code to response my main file,
FileStream fs = File.OpenRead(string.Format("{0}/neg.acc",
Settings.Default.negSourceLocation));
using (StreamReader sr = new StreamReader(fs))
{
string jsContent = sr.ReadToEnd();
context.Response.Write(jsContent);
}
I need my 2nd file to be read right after the main is done.
An easy way to explain it:
lets assume main file contains : "hello"
and 2nd file contains: "what a beautiful day"
my response should be:
"hello"
"what a beautiful day"
Thanks in advance
FileStream is also a disposable object like StreamReader. Best to wrap that in a using statement too. Also to make the code a little more reusable, place the code to read the text file into its own method, something like:
public static string CombineFilesText(string mainPath, string clientPath)
{
string returnText = ReadTextFile(mainPath);
returnText += ReadTextFile(clientPath);
return returnText;
}
private static string ReadTextFile(string filePath)
{
using (FileStream stream = File.OpenRead(filePath))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string File1 = #"c:\temp\MyTest1.txt";
string File2 = #"c:\temp\MyTest2.txt";
if (File.Exists(File1))
{
string appendText = File.ReadAllText(File1);
if (File.Exists(File2))
{
appendText += File.ReadAllText(File2);
}
}
}
}
seems like your question needs asp.net tag
context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg.acc");
context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg2.acc");
https://msdn.microsoft.com/en-us/library/dyfzssz9
This is what I did, not sure its the right way using C#,
static public string CombineFilesText(string mainPath, string clientPath)
{
string returnText = "";
FileStream mfs = File.OpenRead(mainPath);
using (StreamReader sr = new StreamReader(mfs))
{
returnText += sr.ReadToEnd();
}
FileStream cfs = File.OpenRead(clientPath);
using (StreamReader sr = new StreamReader(cfs))
{
returnText += sr.ReadToEnd();
}
return returnText;
}

How to read StreamReader text line by line

I have a text file hosted and this file have a organized string like this:
First line
Second line
Third line
Fourth line
Sixth line
Seventh line
....................
I'm getting all content from this file with following function:
private static List<string> lines;
private static string DownloadLines(string hostUrl)
{
var strContent = "";
var webRequest = WebRequest.Create(hostUrl);
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
strContent = reader.ReadToEnd();
}
lines = new List<string>();
lines.Add(strContent);
return strContent;
}
// Button_click
DownloadLines("http://address.com/folder/file.txt");
for (int i = 0; i < lines.Count; i++)
{
lineAux = lines[0].ToString();
break;
}
Console.WriteLine(lineAux);
Then, how I can access for example the first index like text inside this large organized string that is returned by this method?
You can read text file line by line this way
private static List<string> DownloadLines(string hostUrl)
{
List<string> strContent = new List<string>();
var webRequest = WebRequest.Create(hostUrl);
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
while (!reader.EndOfStream)
{
strContent.Add(reader.ReadLine());
}
}
return strContent;
}
after returning this list from the method you can access the text line using list index

How to write into an existing textfile in windows phone?

If this is the code in opening a textfile "word.txt" in my solution explorer.
Stream txtStream = Application.GetResourceStream(new Uri("/sample;component/word.txt", UriKind.Relative)).Stream;
using (StreamReader sr = new StreamReader(txtStream))
{
string jon;
while (!sr.EndOfStream)
{
jon = sr.ReadLine();
mylistbox.ItemSource = jon;
}
}
How do i write and append in the existing textfile?
Here is an example
public static void WriteBackgroundSetting(string currentBackground)
{
const string fileName = "RecipeHub.txt";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if(myIsolatedStorage.FileExists(fileName))
myIsolatedStorage.DeleteFile(fileName);
var stream = myIsolatedStorage.CreateFile(fileName);
using (StreamWriter isoStream = new StreamWriter(stream))
{
isoStream.WriteLine(currentBackground);
}
}
}

Writing a file adding random characters to start of each line

I'm overwriting a file using C# in Windows Phone 7. When I do this a seemingly random character is added to the start of each line.
Why is this happening?
Code:
public static bool overwriteFile(string filename, string[] inputArray)
{
try
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
FileStream stream = store.OpenFile(filename, FileMode.Create);
BinaryWriter writer = new BinaryWriter(stream);
foreach (string input in inputArray)
{
writer.Write(input + "\n");
}
writer.Close();
return true;
}
catch (IOException ex)
{
return false;
}
}
Lodaing Code:
public static Idea[] getFile(string filename)
{
try
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
string fileContents = null;
if (store.FileExists(filename)) // Check if file exists
{
IsolatedStorageFileStream save = new IsolatedStorageFileStream(filename, FileMode.Open, store);
StreamReader streamReader = new StreamReader(save);
fileContents = streamReader.ReadToEnd();
save.Close();
}
string[] lines = null;
if (fileContents != null)
{
lines = fileContents.Split('\n');
}
Idea[] ideaList = null;
if (lines != null)
{
ideaList = new Idea[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
ideaList[i] = new Idea(lines[i].TrimEnd('\r'));
}
}
return ideaList;
}
catch (IOException ex)
{
return null;
}
}
The random character is a length prefix; see http://msdn.microsoft.com/en-us/library/yzxa6408.aspx.
You should be using some type of TextWriter to write strings to the file; NOT a BinaryWriter.
A StreamWriter might be the best and then you could use the WriteLine method.
Instead of using '\n', try using Environment.NewLine
You are using a BinaryWriter to write, and a TextReader to read. Change your write code to use a StreamWriter (which is a TextWriter) instead of a BinaryWriter. This will also get you the WriteLine method that Naveed recommends.
try changing this
writer.Write(input + "\n");
to
writer.WriteLine(input);

Categories