writing to a text file and reading that text file
I have used this code
var dest1 = File.AppendText(Path.Combine(_logFolderPath, "log1.txt"));
dest1.WriteLine(line.Trim());
to write to a text file log1.txt after that i have to read this text file...
i have declared in a variable... I know this is not possible..but i dont know how
using (var file = File.OpenText(dest1))
How to open that text file and read that file by using
while ((line2 = file.ReadLine()) != null)
Any suggestion??
EDIT:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select codesnippet from edk_custombrsnippet_vw", con);
DataTable dt = new DataTable();
da.Fill(dt);
string line = dt.Rows[0].ItemArray[0].ToString().Replace("\n", Environment.NewLine).Replace("\r", Environment.NewLine);
;
//MessageBox.Show(line);
string Filepath2 = TextBox1.Text;
int counter = 1;
string line2;
if (File.Exists(Filepath2) )
{
DirectoryInfo Folder = new DirectoryInfo(textboxPath.Text);
var _logFolderPath = Path.Combine(textboxPath.Text.Trim(), "log");
if (Folder.Exists)
if开发者_运维百科 (!Directory.Exists(_logFolderPath))
Directory.CreateDirectory(_logFolderPath);
string filename = Path.Combine(_logFolderPath, "log1.txt");
var dest1 = File.AppendText(filename);
dest1.WriteLine(line.Trim());
using (var file = File.OpenText(filename))
{
using (var file2 = File.OpenText(Filepath2))
{
bool time = false;
while ((line2 = file2.ReadLine()) != null)
{
using (var dest = File.AppendText(Path.Combine(_logFolderPath, "log.txt")))
{
if (!time)
{
dest.WriteLine("");
dest.WriteLine("---------------------" + DateTime.Now + "---------------------");
time = true;
}
bool patternwritten = false;
while ((line = file.ReadLine()) != null)
{
if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
{
if (!patternwritten)
{
dest.WriteLine("");
dest.WriteLine("Pattern Name : " + line2);
patternwritten = true;
}
dest.WriteLine("LineNo : " + counter.ToString() + " : " + " " + line.Trim());
}
counter++;
}
//FilePath.BaseStream.Seek(0, SeekOrigin.Begin);
counter = 1;
}
}
}
}
Store the filename in a variable like so:
string filename = Path.Combine(_logFolderPath, "log1.txt");
Then use it in the following lines:
var dest1 = File.AppendText(filename);
...
using (var file = File.OpenText(filename))
Then the rest should work as expected. In your code above you were trying to pass a StreamWriter to the File.OpenText method which is wrong.
You're not closing the file after writing to it, so your program still has an open handle to the file, which means that you can't open another handle to read from it.
This bit:
var dest1 = File.AppendText(filename);
dest1.WriteLine(line.Trim());
should be:
using (var dest1 = File.AppendText(filename))
{
dest1.WriteLine(line.Trim());
}
精彩评论