im trying to edit an HTML i have created.
having the user typing something into the text box it will change the value but then I want it to reset.
I got the part of making the text change but it stays like that and when i try it for the 2nd time it does not work without me manually editing the .html file
here's my code:
const string fileName = "txt.html";
var content = File.ReadAllText(fileName);
content = content.Replace("{0}", textBox1.Text);
File.WriteAllText(fileName, content);
Process.Start(fileName);
I tried adding something like this after that code but its just opening with the variable ' {0} '
var content2 = File.ReadAllText(fileName);
content2 = content2.Replace(textBox1.Text, "{0}");
File.WriteAllText(fileName, content2);
you need a template html file, every time replace value using that template
const string fileName = "txt.html";
const string templateFileName = "txtTemplate.html";
var content = File.ReadAllText(templateFileName );
content = content.Replace("{0}", textBox1.Text);
File.WriteAllText(fileName, content);
Process.Start(fileName);
Related
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;
}
I have a template I'm using to print labels, what I'm currently doing is a Replace() on the variable parts of my template and print it as is.
What is the best way to recover the original template after printing ? Revert manually all the changes ? Not modifying the template at first but create a copy that I modify, print and delete ?
The template looks like :
data1 : $1
data2 : $2
data3 : $3
data4 : $4
and then Replace() + print with :
string text = File.ReadAllText(filePath);
text = text.Replace("$1", textBoxNumOF.Text);
text = text.Replace("$2", designation);
text = text.Replace("$3", textBoxNumOF.Text.Substring(textBoxNumOF.Text.Length - 4));
text = text.Replace("$4", "1");
File.WriteAllText(filePath, text, UTF8Encoding.UTF8);
PrintDialog pd1 = new PrintDialog();
pd1.PrinterSettings = new PrinterSettings();
EnvoiImpression.SendFileToPrinter(#"Datamax-O'Neil H-4310 (Copie 1)", filePath);
Read your template and write the output which you are sending to the printer into a temp file inside the temp directory of windows.
Please see the following function:
public static string GetTempFile()
{
// get temporary path
var tempPath = Path.GetTempPath();
// get temporary filename
string tempFileName = Path.GetRandomFileName();
//combine
return Path.Combine(tempPath, tempFileName);
}
This way you do not need to revert your template and comply with the rules for temporary files on Windows. I suggest that you remember the files for deleting all your temporary files again from disk after your program / method was successful.
The function
EnvoiImpression.SendFileToPrinter(#"Datamax-O'Neil H-4310 (Copie 1)", filePath);
is sadly unknown to my. But perhaps there is also an overload which does accept a Stream? If so, you could edit your template in a MemoryStream and do not even need to write to the disk.
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);
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();
}
}
How to prepend/append text beginning of the existing data in a text file.
Basically i need to provide a header before this data in a text file. This header is a dynamic data. Please note this data is coming from external source or SQL package or from somewhere. So After getting data in a text file then i want to provide a header text with comma separated in the existing entries/data of a text file.
I've sample data in a text file as below:
123,"SAV","CBS123",2010-10-10 00:00:00
456,"CUR","CBS456",2012-02-01 00:00:00
Header text to Prepend:
HDR<TableName><DateTime>
Output i need as below:
TableName: Account
DateTime: 2012-05-09 12:52:00
HDRAccount2012-05-09 12:52:00
123,"SAV","CBS123",2010-10-10 00:00:00
456,"CUR","CBS456",2012-02-01 00:00:00
Please help me how to get the same in both languages VB6.0, C#.NET
Note that you can't technically 'insert' into a file and have all contents 'shift' down. Best you can do is read the file and rewrite it with a new line. Here's one way to do it efficiently:
static void InsertHeader(string filename, string header)
{
var tempfile = Path.GetTempFileName();
using (var writer = new StreamWriter(tempfile))
using (var reader = new StreamReader(filename))
{
writer.WriteLine(header);
while (!reader.EndOfStream)
writer.WriteLine(reader.ReadLine());
}
File.Copy(tempfile, filename, true);
File.Delete(tempfile);
}
Credits to this answer for the idea but improved enough to make it worth posting separately.
Now if you want something that accepts the table name and date time, just add this as a second function:
static void InsertTableHeader(string filename, string tableName, DateTime dateTime)
{
InsertHeader(filename,
String.Format("HDR{0}{1:yyyy-MM-dd HH:MM:ss}",
tableName,
dateTime));
}
So just call InsertHeader(filename, "Account", DateTime.Now) or similar as needed.
var fn = #"c:\temp\log.csv";
var hdr1 = "Account";
var hdr2 = "2012-05-09 12:52:00";
System.IO.File.WriteAllText(fn, System.String.Format("HDR {0} {1}\n{2}", hdr1, hdr2, System.IO.File.ReadAllText(fn)))
String[] headerLines = new String[]{"HDR<TableName><DateTime>"};
String filename = "1.txt";
var newContent = headerLines.Union(File.ReadAllLines(filename));
File.WriteAllLines(filename, newContent);
VB6 translation of yamen's answer. Air code! I haven't compiled this, much less run
it!
Sub InsertHeader(ByVal filename As String, ByVal header As String)
Dim tempfile As String
Dim readUnit As Integer
Dim writeUnit As Integer
tempfile = "c:\tempfile" '' TODO generate better temporary filename -
'' here is a link to help with getting path of temporary directory
'' http://vb.mvps.org/samples/SysFolders
readUnit = FreeFile
Open filename For Input As #readUnit
writeUnit = FreeFile
Open tempfile For Output As #writeUnit
Print #writeUnit, header
Do Until Eof(readUnit)
Dim nextLine As String
Line Input #readUnit, nextLine
Print #writeUnit, nextLine
Loop
Close readUnit
Close writeUnit
Kill filename
FileCopy tempfile, filename
Kill tempfile
End sub
You can do it in the reverse order of the 1st answere, meanse first your write the header in text file then open that text file in append mode and then woirite the data ..for opening the file in append mode use following code line:
FileStream aFile = new FileStream(filePath, FileMode.Append,
FileAccess.Write);
StreamWriter sw = new StreamWriter(aFile);
sw.Write(text);
sw.Close();
aFile.Close();