i have stored the txt file to sql server database .
i need to read the txt file line by line to get the content in it.
my code :
DataTable dtDeleteFolderFile = new DataTable();
dtDeleteFolderFile = objutility.GetData("GetTxtFileonFileName", new object[] { ddlSelectFile.SelectedItem.Text }).Tables[0];
foreach (DataRow dr in dtDeleteFolderFile.Rows)
{
name = dr["FileName"].ToString();
records = Convert.ToInt32(dr["NoOfRecords"].ToString());
bytes = (Byte[])dr["Data"];
}
FileStream readfile = new FileStream(Server.MapPath("txtfiles/" + name), FileMode.Open);
StreamReader streamreader = new StreamReader(readfile);
string line = "";
line = streamreader.ReadLine();
but here i have used the FileStream to read from the Particular path. but i have saved the txt file in byte format into my Database. how to read the txt file using the byte[] value to get the txt file content, instead of using the Path value.
Given th fact that you have the file in a byte array, you can make use of MemoryStream Class
Something like
using (MemoryStream m = new MemoryStream(buffer))
using (StreamReader sr = new StreamReader(m))
{
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
}
}
Also make sure to use using Statement (C# Reference)
Defines a scope, outside of which an
object or objects will be disposed.
The using statement allows the
programmer to specify when objects
that use resources should release
them. The object provided to the using
statement must implement the
IDisposable interface. This interface
provides the Dispose method, which
should release the object's resources.
You could try something like this at the end of your foreach:
String txtFileContent = Encoding.Unicode.GetString((Byte[])dr["Data"]);
Related
I'm using C# to open a text file then I read everything inside it with this code:
OpenFileDialog pic = new OpenFileDialog();
pic.ShowDialog();
System.IO.StreamReader file = new System.IO.StreamReader(pic.OpenFile());
a=file.readline();
After I've finished reading, I want to read the data again but it tells me it's empty - how can I read it again?
Try something like this
var openDialog = new OpenFileDialog();
if (openDialog.ShowDialog == DialogResult.OK)
{
using (var stream = File.OpenRead(openDialog.FileName)
{
//read everything here
}
}
My guess is that the file only contains 1 line and so once you've read it there's nothing left to read. If you want to read the same line again you'll need to close the file and open it again. You should also be using a 'using' statement around the stream reader to ensure it is correctly disposed of, so something like:
string a = string.Empty;
using(StreamReader reader = new StreamReader(pic.FileName))
{
a = reader.ReadLine();
}
I want to read a simple CSV file with comma separated with this code:
var reader = new StreamReader(File.OpenRead(#"d:\34.csv"));
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listB.Add(values[1]);
}
MessageBox.Show("READ IT!!!");
But when I read the file an debug that code,attention can not read Persian or Arabic character! How can I solve that? I think my file is not valid encoding?
if your CSV file contains just one line the ReadToEnd could be acceptable, but if you have a log file composed by more than one line then it is better to read line by line using ReadLine of the StreamReader object
link for true answer and more information
using (StreamReader sr = new StreamReader("c:/temp/34.csv"))
{
string currentLine;
// currentLine will be null when the StreamReader reaches the end of file
while((currentLine = sr.ReadLine()) != null)
{
// Search, case insensitive, if the currentLine contains the searched keyword
if(currentLine.IndexOf("I/RPTGEN", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
Console.WriteLine(currentLine);
}
}
}
More information
You can create a class composed of get and set for each line of the CSV . You can then instantiate an object list to retrieve the CSV lines.
Try this way :
class Program
{
static void Main(string[] args)
{
var reader = new StreamReader(File.OpenRead(#"YourCSV"),Encoding.Unicode);
List<Customer> customer = new List<Customer>();
while (!reader.EndOfStream)
{
Customer c = new Customer
{
m_line1 = null,
m_line2 = null,
};
var line = reader.ReadLine();
var tokens = line.Split(',');
c.m_line1 = tokens[0];
c.m_line2 = tokens[1];
customer.Add(c);
}
foreach(var s in customer)
{
Console.Writline(s);
Console.Readline();
}
}
}
class Customer
{
private string line1;
public string m_line1
{
get
{
return line1;
}
set
{
line1= value;
}
}
private string line2;
public string m_line2
{
get
{
return line2;
}
set
{
line2= value;
}
}
You will have to pass the character encoding to the StreamReader constructor. There is no such thing as plain text. Reading text requires knowing its encoding.
The line
using (StreamReader sr = new StreamReader("c:/temp/34.csv"))
should be
using (StreamReader sr = new StreamReader("c:/temp/34.csv"), myencoding)
what myencoding is is something only you can know. With what encoding was the file saved? That's the encoding you need there. If the file was generated on Windows, and educated guess of the most likely encoding would be it is UTF-16LE. That encoding is available as Encoding.Unicode - which is a bad name, it should have been Encoding.UTF16LE, but that's the name the .NET framework uses.
Other possible encodings that are supported by StreamReader are listed on https://msdn.microsoft.com/en-us/library/System.Text.Encoding_properties(v=vs.110).aspx
If you don't know with what encoding the file was saved, some encodings leave hints in the form of a Byte order mark sometimes abbreviated to BOM. A byte order mark are the first few bytes of a text document that tell you its encoding. You can find more information on the byte order mark, and some of its values on http://en.wikipedia.org/wiki/Byte_order_mark
Relying on the BOM is generally a bad idea, because
it's not a full-proof solution: some encodings don't use a BOM, or make the BOM optional
Even if you successfully determine the encoding, that doesn't mean that StreamReader knows how to handle that encoding (though this is unlikely, but possible)
the BOM might not be a BOM at all, but be part of the actual text (also unlikely but possible)
In some cases it is impossible to know the encoding of a file, notably if the file comes from a file upload on the web, or if someone just mailed you the file, and they don't know how they encoded it. This can be a good reason not to allow "plain text" uploads (which is reasonable because, it can do with a little repetition, there is no such thing as plain text).
tl;dr: The most likely thing to work is one of
using (StreamReader sr = new StreamReader(File.OpenRead(#"c:/temp/34.csv"),Encoding.Unicode) {
...
}
or
using (StreamReader sr = new StreamReader(File.OpenRead(#"c:/temp/34.csv"),Encoding.UTF8)
or
using (StreamReader sr = new StreamReader(File.OpenRead(#"c:/temp/34.csv"),Encoding.UTF32)
I have a file which contains several text entries, say
one
two
three
Now, I need to delete one of the entries, say "two". I'm using StreamReader and StreamWriter classes. In order to delete, first, I read the contents of the file into a string using StreamReader class, replace the "two\r\n" in the read string with "" and then, I write this string to the file using the StreamWriter class. But, since the length of the newly written string i.e. "one\r\nthree\r\n" is less than the original string i.e. "one\r\ntwo\r\nthree\r\n", the first few characters get overwritten and the characters near the end still stay there giving rise to "one\r\nthree\r\nree\r\n". Seems like a simple problem but, it has me stuck. Any ideas?
The user variable contains the entry to be deleted.
string all = "";
using (IsolatedStorageFileStream isoStream = store.OpenFile("user_list", FileMode.Open))
{
using (StreamReader sr = new StreamReader(isoStream))
{
all = sr.ReadToEnd();
all = all.Replace(user + "\r\n", "");
}
}
using (IsolatedStorageFileStream isoStream = store.OpenFile("user_list", FileMode.Open))
{
using (StreamWriter sw = new StreamWriter(isoStream))
{
sw.Write(all);
sw.Flush();
}
}
You can fix the problem by changing FileMode.Open to FileMode.Create when you're opening the output file. That is:
using (IsolatedStorageFileStream isoStream =
store.OpenFile("user_list", FileMode.Create))
That will overwrite the previous file.
I have code that reads a file and then converts it to a string, the string is then written to a new file, although could someone demonstrate how to append this string to the destination file (rather than overwriting it)
private static void Ignore()
{
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
Console.WriteLine(myString);
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
file.WriteLine(myString);
file.Close();
}
If the file is small, you can read and write in two code lines.
var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);
If the file is huge, you can read and write line-by-line:
using (var source = new StreamReader("c:\\test.txt"))
using (var destination = File.AppendText("c:\\test2.txt"))
{
var line = source.ReadLine();
destination.WriteLine(line);
}
using(StreamWriter file = File.AppendText(#"c:\test2.txt"))
{
file.WriteLine(myString);
}
Use File.AppendAllText
File.AppendAllText("c:\\test2.txt", myString)
Also to read it, you can use File.ReadAllText to read it. Otherwise use a using statement to Dispose of the stream once you're done with the file.
Try
StreamWriter writer = File.AppendText("C:\\test.txt");
writer.WriteLine(mystring);
I have a few multimillion lined text files located in a directory, I want to read line by line and replace “|” with “\” and then write out the line to a new file. This code might work just fine but I’m not seeing any resulting text file, or it might be I’m just be impatient.
{
string startingdir = #"K:\qload";
string dest = #"K:\D\ho\jlg\load\dest";
string[] files = Directory.GetFiles(startingdir, "*.txt");
foreach (string file in files)
{
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(file, FileMode.Open))
using (StreamReader rdr = new StreamReader(fs))
{
while (!rdr.EndOfStream)
{
string begdocfile = rdr.ReadLine();
string replacementwork = docfile.Replace("|", "\\");
sb.AppendLine(replacementwork);
FileInfo file_info = new FileInfo(file);
string outputfilename = file_info.Name;
using (FileStream fs2 = new FileStream(dest + outputfilename, FileMode.Append))
using (StreamWriter writer = new StreamWriter(fs2))
{
writer.WriteLine(replacementwork);
}
}
}
}
}
DUHHHHH Thanks to everyone.
Id10t error.
Get rid of the StringBuilder, and do not reopen the output file for each line:
string startingdir = #"K:\qload";
string dest = #"K:\D\ho\jlg\load\dest";
string[] files = Directory.GetFiles(startingdir, "*.txt");
foreach (string file in files)
{
var outfile = Path.Combine(dest, Path.GetFileName(file));
using (StreamReader reader = new StreamReader(file))
using (StreamWriter writer = new StreamWriter(outfile))
{
string line = reader.ReadLine();
while (line != null)
{
writer.WriteLine(line.Replace("|", "\\"));
line = reader.ReadLine();
}
}
}
Why are you using a StringBuilder - you are just filling up your memory without doing anything with it.
You should also move the FileStream and StreamWriter using statements to outside of your loop - you are re-creating your output streams for every line, causing unneeded IO in the form of opening and closing the file.
Use Path.Combine(dest, outputfilename), from your code it looks like you're writing to the file K:\D\ho\jlg\load\destouputfilename.txt
This code might work just fine but I’m not seeing any resulting text file, or it might be I’m just be impatient.
Have you considered having a Console.WriteLine in there to check the progress. Sure, it's going to slow down performance a tiny tiny bit - but you'll know what's going on.
It looks like you might want to do a Path.Combine, so that instead of new FileStream(dest + outputfilename), you have new FileStream(Path.Combine(dest + outputfilename)), which will create the files in the directory that you expect, rather than creating them in K:\D\ho\jlg\load.
However, I'm not sure why you're writing to a StringBuilder that you're not using, or why you're opening and closing the file stream and stream writer on each line that you're writing, is that to force the writer to flush it's output? If so, it might be easier to just flush the writer/stream on each write.
you're opening and closing the output strean for each line in the output, you'll have to be very patient!
open it once outside the loop.
I guess the problem is here:
string begdocfile = rdr.ReadLine();
string replacementwork = docfile.Replace("|", "\\");
you're reading into begdocfile variable but replacing chars in docfile which I guess is empty
string replacementwork = docfile.Replace("|", "\\");
I believe the above line in your code is incorrect : it should be "begdocfile.Replace ..." ?
I suggest you focus on getting as much of the declaration and "name manufacture" out of the inner loop as possible : right now you are creating new FileInfo objects, and path names for every single line you read in every file : that's got to be hugely expensive.
make a single pass over the list of target files first, and create, at one time, the destination files, perhaps store them in a List for easy access, later. Or a Dictionary where "string" will be the new file path associated with that FileInfo ? Another strategy : just copy the whole directory once, and then operate to directly change the copied files : then rename them, rename the directory, whatever.
move every variable declaration out of that inner loop, and within the using code blocks you can.
I suspect you are going to hear from someone here at more of a "guru level" shortly who might suggest a different strategy based on a more profound knowledge of streams than I have, but that's a guess.
Good luck !