How to open txt file on localhost and change is content - c#

i want to open a css file using C# 4.5 and change only one file at a time.
Doing it like this gives me the exception - URI formats are not supported.
What is the most effective way to do it ?
Can I find the line and replace it without reading the whole file ?
Can the line that I am looking and than start to insert text until
cursor is pointing on some char ?
public void ChangeColor()
{
string text = File.ReadAllText("http://localhost:8080/game/Css/style.css");
text = text.Replace("class='replace'", "new value");
File.WriteAllText("D://p.htm", text);
}

I believe File.ReadAllText is expecting a file path, not a URL.
No, you cannot search/replace sections of a text file without reading and re-writing the whole file. It's just a text file, not a database.

most effective way to do it is to declare any control you want to alter the css of as "runat=server" and then modify the CssClass property of it. There is no known alternative way to modify the css file directly. Any other hacks is just that.. a hack and very innefficient way to do it.

As mentioned before File.ReadAllText does not support url. Following is a working example with WebRequest:
{
Uri uri = new Uri("http://localhost:8080/game/Css/style.css");
WebRequest req = WebRequest.Create(uri);
WebResponse web = req.GetResponse();
Stream stream = web.GetResponseStream();
string content = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
content.Replace("class='replace'", "new value");
using (StreamWriter sw = new StreamWriter("D://p.htm"))
{
sw.Write(content);
sw.Flush();
}
}

Related

How to read HTML template, replace text and convert back to HTML

I am currently loading a html file from a filepath and reading it as text. I then replace certain characters in the file itself and I want to convert it back to html.
This is how I do it currently:
HtmlDocument document = new HtmlDocument();
document.Load(#message.Location);
content = document.DocumentNode.OuterHtml;
//Code to replace text
var eContent = HttpUtility.HtmlEncode(content);
When I debug and check what eContent holds, I can see newline characters like "\r\n". If I copy and paste the text into a .html file, only the text appears, not a proper html page.
I'm using Html AgilityPack already and am unsure of what else I need to do.
EDIT:
I have also tried
var result = new HtmlString(content);
HtmlAgilityPack is great to read and modify Html files you cannot create readable output.
Try with this
I have done this before using...
string savePath = "path to save html file, ie C://myfile.html";
string textRead = File.ReadAllText(#"Path of original html file");
//replace or manipulate as needed... ie textRead = textRead.Replace("", "");
File.WriteAllText(savePath, textRead);
Try to use ContentResult, which inherits ActionResult. Just remember to set ContentType to text/html.
[HttpGet]
public IActionResult FileToTextToHtml()
{
string fileContents = System.IO.File.ReadAllText("D:\\HtmlTest.html");
var result= new ContentResult()
{
Content = fileContents,
ContentType = "text/html",
};
return result;
}

Append Text at exact location in text

I was looking to append text to a exact location in a text file. I have used StreamReader to find the text in the file I am looking for. I thought about using StreamWriter but that obviously doesn't make sense. I was hoping to find some "append" method in some class somewhere that would help me do this but with now success. Or is there a better way to do this than to use StreamReader?
using (StreamReader sr = new StreamReader(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("VAR_GLOBAL CONSTANT"))
{
//append text before this variable
// e.g. (*VAR_GLOBAL CONSTANT
// append the (* before VAR_GLOBAL CONSTANT
}
if (line.Contains("END_VAR"))
{
//append text after this variable
// e.g. END_VAR*)
// append the *) after END_VAR
}
}
}
Does anyone have any thoughts on how to accomplish this?
One way to do it would be to read the file contents into a string, update the contents locally, and then write it back to the file again. This probably isn't very feasible for really large files, especially if the appending is done at the end, but it's a start:
var filePath = #"f:\public\temp\temp.txt";
var appendBeforeDelim = "VAR_GLOBAL CONSTANT";
var appendAfterDelim = "END_VAR";
var appendBeforeText = "Append this string before some text";
var appendAfterText = "Append this string after some text";
var newFileContents = File.ReadAllText(filePath)
.Replace(appendBeforeDelim, $"{appendBeforeText}{appendBeforeDelim}")
.Replace(appendAfterDelim, $"{appendAfterDelim}{appendAfterText}");
File.WriteAllText(filePath, newFileContents);

StreamReader.ReadToEnd returns file path

I have a strange problem with StreamReader. My program is a console program and it should loop through a directory structure for all *.cs file. Then check if a specific word is in the file and write the file path to output.
using (StringReader sr = new StringReader(fPath))
{
string content = sr.ReadLine(); // sr.ReadToEnd();
Debug.WriteLine(content);
int found = content.IndexOf(p);
if (found != -1)
{
result = true;
}
}
This is the code that I use to find the work in a specific file.
The problem is that sr.ReadToEnd (but also ReadLine) returns the value of fPath not the content of the file!
The file exists and is not locked.
If fPath is:
"C:\TEMP\DC_LV1_LaMine_Mk2Plus_134_ix220_20160404\Alarm.Script.cs"
content will be:
"C:\TEMP\DC_LV1_LaMine_Mk2Plus_134_ix220_20160404\Alarm.Script.cs"
Can anyone see what I have done wrong?
You are using StringReader instead of StreamReader
StringReader implements a TextReader that reads from a string
StramReader implements a TextReader that reads characters from a byte stream in a particular encoding
If you want to read from a file use this constructor for StreamReader
You could also use File.ReadAllText if the file is small and you have enough resources to read it all at once
For a more comprehensive overview, see this article

Saving File on Desktop by c#

I am using a web service that returns me some data. I am writing that data in a text file. my problem is that I am having a file already specified in the c# code, where I want to open a dialog box which ask user to save file in his desired location. Here I am posting code which I have used. Please help me in modifying my code. Actually after searching from internet, all are having different views and there is lot of changes in code required where as I do not want to change my code in extent. I am able to write the content in test file but how can I ask user to enter his desire location on computer?
StreamWriter file = new StreamWriter("D:\\test.txt");
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
// Get the response from the Internet resource.
HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
// Read the body of the response from the server.
StreamReader strm =
new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
string content = "";
for (int i = 0; i < symbols.Length; i++)
{
// Loop through each line from the stream,
// building the return XML Document string
if (symbols[i].Trim() == "")
continue;
content = strm.ReadLine().Replace("\"", "");
string[] contents = content.ToString().Split(',');
foreach (string dataToWrite in contents)
{
file.WriteLine(dataToWrite);
}
}
file.Close();
Try this
using (WebClient Client = new WebClient ())
{
Client.DownloadFile("http://www.abc.com/file/song/a.mpeg", "a.mpeg");
}

How do you in C# read a text file for a specific string, and if it doesnt exist write it

I know how to read append and write with Streamreader/Steamwriter. But I am having issues with getting my program to read the text file and check for a specific string of data. If it doesnt exist write it at the end. Any Ideas? Im trying to do this to a specific file, via web page button using Server.MapPath.
This how you read file and check
using (StreamReader sr = new StreamReader(path));
{
string contents = sr.ReadToEnd();
if (contents.Contains(//string to check//))
{
appendtofile("add string")
}
}
and here is how you append
public void appendtofile(string text)
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(text);
}
}

Categories

Resources