Reading Data From File Gets Corrupted - streamwriter

I am reading data from a TXT file that requires me to replace some of the existing data, and then write it back to the file. The issue is, there are special characters in the file that get corrupted when I write the text back to the file.
For example, I have a string in a file "foo.txt" that has the following "€rdrf +À [HIGH]". My application reads the text into a string, goes through the line and replaces [HIGH] with a value, and then writes back to the file. The issue is, the special text characters get corrupted.
Here is an abbreviated version of the code base:
string fileText = System.IO.File.ReadAllText("foo.txt");
fileText= iPhoneReferenceText.Replace("[HIGH]", low);
TextWriter tw = new StreamWriter("Path");
tw.WriteLine(fileText);
tw.Close();
How do I read from the file without corrupting the special text characters?
Thanks
Jay

You need an appropriate Encoding I think
string fileText = System.IO.File.ReadAllText("foo.txt", Encoding.XXXX);
.
.
tw = new StreamWriter("path", Encoding.XXXX);
.
.
Where XXXX is one of:
System.Text.ASCIIEncoding
System.Text.UnicodeEncoding
System.Text.UTF7Encoding
System.Text.UTF8Encoding

Try this :
string filePath = "your file path";
StreamReader reader = new StreamReader(filePath);
string text = reader.ReadToEnd();
// now you edit your text as you want
string updatedText = text.Replace("[HIGH]", "[LOW]");
reader.Dispose(); //remember to dispose the reader so you can overwrite on the same file
StreamWriter writer = new StreamWriter(filePath);
writer.Write(text, 0, text.Length);
writer.Dispose(); //dispose the writer
Console.ReadLine();
Remember to Dispose after finishing from the reader and the writer.

Related

How to read a textfile line by line from FTP server?

I have wriiten some code for reading textfiles from ftp server, without downloading to the local system. Now i need to display it line by line.. is it possible?
WebClient request = new WebClient();
request.Credentials = new NetworkCredential("***", "edddd");
byte[] newFileData = request.DownloadData(url);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
ListBox1.Items.Add(fileString);
Sure! Split your file contents on new line.
var lines = fileString.Split(new string[] { "\r\n", "\n" },
StringSplitOptions.None);
Then use the array of lines returned to display as your line. Each could be an item in your list box.

is there a way to query a stream in c#, ex. select * from a streamobject

I have a file upload control in my asp.net (c#) website, which is used to upload csv files with data to be inserted into the database, my problem is that, I was not able to get the actual path of the uploaded file
It always gave me: C:\inetput\projectfolder\csvname.csv
where it should have been similar to: C:\Documents and settings\Pcname\Desktop\csvname.csv
but by going through the various post of file upload, i came to know that file need to be saved on the server first,
using Fileupload1.Saveas(savepath);
which is mandatory to save the file in a previously specified location, where this not actually required. (since it will increase the overhead of again deleting the file).
then what I do is as below:
bool result = true;
strm = FileUpload1.PostedFile.InputStream;
reader2 = new System.IO.StreamReader(strm);
// **** new ****
FileInfo fileinfo = new FileInfo(FileUpload1.PostedFile.FileName);
string savePath = "c:\\"; // example "c:\\temp\\uploads\\"; could be any path
string fileName = fileinfo.Name;
string strFilePath = savePath.ToString();
savePath += fileName;
FileUpload1.SaveAs(savePath);
string strSql = "SELECT * FROM [" + fileinfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";" + "Extended Properties='text;HDR=NO;'";
// load the data from CSV to DataTable
OleDbDataAdapter oleda = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtbCSV = new DataTable();
oleda.Fill(dtbCSV);
if (dtbCSV.Columns.Count != 2)
{
result = false;
}
because I want to count the number of columns in the file, I'm using the oledb reader.
which needs a file to be queried.
Is it possible to Query a stream? I dont want to save the file, instead just read it without saving.
Unfortunately you cannot use OLEDB against a stream.
In situations where it is mandatory to use OLEDB I've managed to write an IDisposable wrapper that would provide a temporary file from a stream and manage deletion.
You could however go for an alternate approach to reading the contents, without saving it, such as parsing the file yourself directly from a stream. I would recommend this instead of the wrapper since you avoid file access restriction problems as well as the overhead of file access.
Here's an SO with several different approaches.

html editor in asp.net ajax 2.0/3.5

can i make html editor of asp.net ajax 2.0/3.5 to read a rtf file from a directory?
can i if yes then how please?
Yes, first; read file content.
// Specify file.
FileStream file = new FileStream(Server.MapPath("~\\files\\test.rtf"), FileMode.OpenOrCreate, FileAccess.Read);
StreamReader sr = new StreamReader(file);
// Read contents of file into a string
string cval = sr.ReadToEnd();
// Second; Set Content property of HTMLEditor.
htmlEditor.Content = cval;
// Close StreamReader
sr.Close();
// Close file
file.Close();

Save string to client with Open/Save dialog

I am using the following code to write the contents of a string (converted to a byte array) to the client in ASP.NET/C#
byte[] data = StrToByteArray(strData);
Response.ClearContent();
Response.AppendHeader("content-length", data.Length.ToString());
Response.ContentType = "text/plain";
Response.AppendHeader("content-Disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(data);
Response.Flush();
fileName is the name of the file ending with the file extension (.pgn). However, the file is saved as a .txt file, ignoring the extension that I am giving it. Would this have to do with the Response.Contenttype = "text/plain"? How can I get the Open/Save dialog to display and save the correct (.pgn) filename?
Also, if filename is a string separated by dashes or spaces, when the Open/Save dialog comes up, the filename is not displayed in its entirety but it is truncated where the first dash (-) or space (or comma) is encountered. How can this be remedied?
Yes, it is saving .txt because of your Content Type (MIME type). Use image/png.
How about you remove the dashes and spaces? String.Replace is great. fileName.Replace("-", ""); etc.

ASP.NET: BOM in Server.Execute()

I'm using this to write to the Response stream:
using (var writer = new StringWriter())
{
context.Server.Execute(virtualpath, writer);
string s = writer.ToString().Replace(...);
context.Response.Write(s);
}
But I'm getting a byte order mark in the response. Am I screwing up the encoding? How do I NOT return the BOM?
EDIT: SOrry Rubens, my first example was incorrect.
Try this:
context.Server.Execute(virtualpath, context.Response.Output);
EDIT: So, try this to force your encoding:
MemoryStream ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms);
context.Server.Execute(virtualpath, writer);
context.Response.Write(Encoding.UTF8.GetString(ms.ToArray()).Replace(...));
Server.Execute() returns an encoded stream, but StringWriter() is intended to store simple .NET strings (which are 16-bit Unicode and don't have a BOM) and doesn't know how to decode the incoming bytes. So, the BOM in the response becomes literal characters in your string.
Try writing to a MemoryStream() instead, then decode that back into a string using whichever encoding (UTF-8 or whatever) that the Server.Execute() is passing back. Then you can parse it and write it back to your Response.

Resources