Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Wednesday, March 28, 2012

Text file

In my table, there is a field which stores the path of a text file (C:\\story.txt).

when i want to retrieve that table with gridview, i want that field will show the all text written in that text file. I mean not the path (C:\\story.txt). Instead it will grab all the text written in that text file. How can i do this?


using (StreamReader stream =newStreamReader(@."c:\story.txt"))

{

string fileContents = stream.ReadToEnd();

}


Plus make sure that ASPNET account as read access to C:/ directory.

HC

text file

I have a text file that i have to read and insert into a database table. The
files has over 30 lines of data in it, I need to start inserting data from
line 8 in the file. How can I start inserting the data from line 8 of my tex
t
file? So from line 1-7 are read only (headers) and starting with line 8 need
s
to be inserted into the table.Hi,
you could use StreamReader which has ReadLine method. You could use it to
skip the first 8 lines, and then go about teading it line by line.
StreamReader.ReadLine
http://msdn.microsoft.com/library/d...adLineTopic.asp
Teemu Keiski
ASP.NET MVP, AspInsider
Finland, EU
http://blogs.aspadvice.com/joteke
"CsharpGuy" <CsharpGuy@.discussions.microsoft.com> wrote in message
news:15EBF9C2-7859-4EEF-A33E-8A64131ABCCC@.microsoft.com...
>I have a text file that i have to read and insert into a database table.
>The
> files has over 30 lines of data in it, I need to start inserting data from
> line 8 in the file. How can I start inserting the data from line 8 of my
> text
> file? So from line 1-7 are read only (headers) and starting with line 8
> needs
> to be inserted into the table.
>

Monday, March 26, 2012

text file

I have a text file that i have to read and insert into a database table. The
files has over 30 lines of data in it, I need to start inserting data from
line 8 in the file. How can I start inserting the data from line 8 of my text
file? So from line 1-7 are read only (headers) and starting with line 8 needs
to be inserted into the table.Hi,

you could use StreamReader which has ReadLine method. You could use it to
skip the first 8 lines, and then go about teading it line by line.

StreamReader.ReadLine
http://msdn.microsoft.com/library/d...adLineTopic.asp

--
Teemu Keiski
ASP.NET MVP, AspInsider
Finland, EU
http://blogs.aspadvice.com/joteke
"CsharpGuy" <CsharpGuy@.discussions.microsoft.com> wrote in message
news:15EBF9C2-7859-4EEF-A33E-8A64131ABCCC@.microsoft.com...
>I have a text file that i have to read and insert into a database table.
>The
> files has over 30 lines of data in it, I need to start inserting data from
> line 8 in the file. How can I start inserting the data from line 8 of my
> text
> file? So from line 1-7 are read only (headers) and starting with line 8
> needs
> to be inserted into the table.

TEXT file as backup

Is it OK to save a backup copy of .CS or VB class file with .TXT extension to avoid errors at build? Thanks.

sure... I do it all the time. as long as you dont expect the app to USE it, your fine.

I save many of my .net files as txt, its handy.

text file format

I need to create a text file which I can get working but i need it to be in
this format which I'm close but not exactly there yet.
format I need:
1234569 BMW
1253252Mercedes
9876522 Lexus
9858252 Jaguar
I'm getting this format:
1234569 BMW
1253252 Mercedes
9876522 Lexus
9858252 Jaguar
here is my code I'm using to write the lines in the text file
string CarSales = string.Format("{0,-9}{1,-8}", VINNumber, CarMake);
file.WriteFile(CarSales);
am I missing something?I got it working I removed the (-) sign.
instead of this:
string CarSales = string.Format("{0,-9}{1,-8}", VINNumber, CarMake);
i did this:
string CarSales = string.Format("{0,9}{1,8}", VINNumber, CarMake);
and now the file lines up correctly
"igotyourdotnet" wrote:

> I need to create a text file which I can get working but i need it to be i
n
> this format which I'm close but not exactly there yet.
> format I need:
> 1234569 BMW
> 1253252Mercedes
> 9876522 Lexus
> 9858252 Jaguar
> I'm getting this format:
> 1234569 BMW
> 1253252 Mercedes
> 9876522 Lexus
> 9858252 Jaguar
> here is my code I'm using to write the lines in the text file
> string CarSales = string.Format("{0,-9}{1,-8}", VINNumber, CarMake);
> file.WriteFile(CarSales);
> am I missing something?
>
>

text file format

I need to create a text file which I can get working but i need it to be in
this format which I'm close but not exactly there yet.

format I need:
1234569 BMW
1253252Mercedes
9876522 Lexus
9858252 Jaguar

I'm getting this format:
1234569 BMW
1253252 Mercedes
9876522 Lexus
9858252 Jaguar

here is my code I'm using to write the lines in the text file
string CarSales = string.Format("{0,-9}{1,-8}", VINNumber, CarMake);
file.WriteFile(CarSales);

am I missing something?I got it working I removed the (-) sign.

instead of this:
string CarSales = string.Format("{0,-9}{1,-8}", VINNumber, CarMake);
i did this:
string CarSales = string.Format("{0,9}{1,8}", VINNumber, CarMake);
and now the file lines up correctly

"igotyourdotnet" wrote:

Quote:

Originally Posted by

I need to create a text file which I can get working but i need it to be in
this format which I'm close but not exactly there yet.
>
format I need:
1234569 BMW
1253252Mercedes
9876522 Lexus
9858252 Jaguar
>
I'm getting this format:
1234569 BMW
1253252 Mercedes
9876522 Lexus
9858252 Jaguar
>
here is my code I'm using to write the lines in the text file
string CarSales = string.Format("{0,-9}{1,-8}", VINNumber, CarMake);
file.WriteFile(CarSales);
>
am I missing something?
>
>
>
>

Text file not being written using System.IO

I'm trying to figure out why when this runs, it runs with no errors but I'm not seeing a txt file outputed to the location I specified. I've replaced some of the filepath with sss for privacy purposes. If the compiler isn't giving any errors, then why isn't it creating the text file? All I see happens is the windows form defined in my code pops up...do I even need that if this is gonna be run as a scheduled task anyway?

What should I look at?


Imports System.IO

Public Class Form1
Inherits System.Windows.Forms.Form
Public Shared Sub Main()
Try
' Create an instance of StreamReader to read from a file.
Dim sr As StreamReader = New StreamReader("\\sss\f$\inetpub\wwwroot\sss\ssis\maintenance\sss\phase2\sss_input\sss_input.txt")
Dim input As String
input = sr.ReadLine()
While Not input Is Nothing

Dim sw As StreamWriter = New StreamWriter("\\sss\f$\inetpub\wwwroot\sss\ssis\maintenance\sss\phase2\sss_output\sss_output_test.txt")
sw.Write(input)
sw.Close()

End While

Catch E As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(E.Message)
End Try
End Sub
End Class

I am not really following the logic there, especially the part where you are saying: "if input is nothing" (if that is the check to see if the file exists, System.IO.File.Exists is a much much better way of checking that)

Outside of that failure to follow your logic, try using a less complicated path to try to write to... for instance, try using "c:\temp", which is local to your application and your app probably has write permissions there... what will this do?
- Well, if your app works, then this tells you that the problem you are hitting is more than likely related to permissions on the other machine
- If your app still doesn't work, something is amiss with your code

Text file question

For example i have a file named textfile.txt Now what i want to do isthat i open that file and read first line(somestring =readline("textfile.txt"); or smth)then second and then third line. Howcan i do it.
VB.NET
Dim strReader as New FileStreamReader("textfile.txt")
While (you still want to read)
somestring = strReader.ReadLine()
DoSomethingWith_somestring
End While
strReader.Close()
- Dan
You could try this code:
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
This code is for a winform, but you can simply use it as you want.
regards

You will want to use the StreamReader class. Below is the link to MSDN.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiostreamreaderclasstopic.asp
Got it all solved... Thank you for your help!

Text File Query

I have an application which searches through a comma-delimited text
file which looks similar to this:
"012233010","PAMIC 6X8","FA","0.000","0.000"
"012233011","PAMIC 8X8","FA","1.000","0.000"
The text file is a dump from an asp/400 system. And it is automatically
ftp-ed to the website.
The question i have is: Is it possible to do a query on the text file
similar to
Select * from INV.txt Where field0 = "1234"
In working with the document in my development environment, I added a
line to the beginning of the file containing all of the column headers.
And everything works perfectly. But my uploaded raw version won't have
the headers included. Thats why i wanted to know if you could run
queries on a text file without column header names using field numbers
instead.
Thanks.
Johnny Authementjpauthement@.gmail.com wrote in news:1135186850.601197.18460
@.g47g2000cwa.googlegroups.com:

> The question i have is: Is it possible to do a query on the text file
> similar to
> Select * from INV.txt Where field0 = "1234"
Yes - you can use Microsoft's Text Driver. It's built into Windows : )
Stan Kee (spamhoneypot@.rogers.com)

Text File Processing

I am currently working on a project in which the user will upload a flat file, text file, for processing and manipulation. I am unable to control the format of the test file because it comes from a packaged software. The file is a fixed delimited file that I must read certain value from and write out a new text file in a new format.
The problem that I am having is the starts with a 12 line header that I can through way because the first 12 line will always be the same. Where my problem is that at certain points during the file a sub set of the header file will occur. There does not seem to be any rhyme or reason as to where the entry occurs.
Does anyone have any idea how how to check for this line pattern and how I can ignore it?What I've done in cases like this is to import the file into anintermediary table, delete any rows which contain header information,and insert the remaining records into the final destination table.

Text File Reverse Read?

Does anyone know of a way to accomplish reading a text file from end to beginning? Like if you wanted to read the last 200 lines from a log file to display on the screen... Can this be done through the framework classes or does this have to be accomplished via a hand made function?I just don't know how to read backwards but you can solve this by writing it backwards and then you can read normally.

To write use:


Dim file As String = "c:\test.txt" 'this must be the name and path of your file
Dim arq As New StreamReader(file)
Dim log_data As String ' this is the content you want to add
Dim cont As String = log_data + arq.ReadToEnd
arq.Close()
Dim arq2 As New StreamWriter("c:\test.txt")
arq2.WriteLine(cont)
arq2.Close()

Then you may read it from the start to the end. You just must to check it's performance.

text file read

I have to read a text file and parse it out to load to a db and I'm having
some issues in doing it. here is what the text file looks like
Dealership number: 98665362236
Location: Maryland
Owner: John Smith
Type: Luxury
BMW, 325i, VIN12363625252362, New,, 20051212. 35400, Ocoonner
Lexus, IS300, VIN6936363633363. Used, Small dent on driver side, 20050112,
24000, JSmith
I need to account the Dealership number
then get the other information starting with BMW, how can I skip line 2 thru
4 and still get teh dealership number and the lines starting with BMW?
so the file is
Make, Model, VIN#, New/Used, any details, date sold,. price and salesmenWell this might be a bit of a brute force method, but if this file is
line by line then couldn't you just read each line into a cell in an
array? Then you could just pick the cells you need to read into your
DB columns? I think that would be the easiest if the file is
segregated into lines like you describe.
HTH
V
When you load a textfile in C#, you get access to a ReadLine() method.
There's no rocket science here.
You need to ReadLine, and look for things you can bank on.
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{ bool isANewCar = false; int lineRowPerSingleCar = 0;
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
lineRowPerSingleCar +=1; if
(line.Substring(0,10).ToUpper() == "DEALERSHIP"{ // figure out a way
to get the last characters, perhaps on the ":" isANewCar =
true;lineRowPerSingleCar = 0; //reset} switch
(lineRowPerSingleCar){ case 2: case 3: case 4: //do
nothing break; default: // do somehting else break;}
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
It's ugly as sin, but that's how you read files, where the format is a
little whack.
Looking at it, I'd use "Dealership number" to signal a new car. And reset
the lineCounter based on that.
Ignore 2, 3, 4, and do something with the rest.
Perhaps the sample above can get you going.
"CsharpGuy" <CsharpGuy@.discussions.microsoft.com> wrote in message
news:223A48D2-C00A-41D9-86D6-A8D5A0F88948@.microsoft.com...
> I have to read a text file and parse it out to load to a db and I'm having
> some issues in doing it. here is what the text file looks like
>
> Dealership number: 98665362236
> Location: Maryland
> Owner: John Smith
> Type: Luxury
> BMW, 325i, VIN12363625252362, New,, 20051212. 35400, Ocoonner
> Lexus, IS300, VIN6936363633363. Used, Small dent on driver side, 20050112,
> 24000, JSmith
> I need to account the Dealership number
> then get the other information starting with BMW, how can I skip line 2
thru
> 4 and still get teh dealership number and the lines starting with BMW?
> so the file is
> Make, Model, VIN#, New/Used, any details, date sold,. price and salesmen
>

text file read

I have to read a text file and parse it out to load to a db and I'm having
some issues in doing it. here is what the text file looks like

Dealership number: 98665362236
Location: Maryland
Owner: John Smith
Type: Luxury
BMW, 325i, VIN12363625252362, New,, 20051212. 35400, Ocoonner
Lexus, IS300, VIN6936363633363. Used, Small dent on driver side, 20050112,
24000, JSmith

I need to account the Dealership number
then get the other information starting with BMW, how can I skip line 2 thru
4 and still get teh dealership number and the lines starting with BMW?
so the file is
Make, Model, VIN#, New/Used, any details, date sold,. price and salesmenWell this might be a bit of a brute force method, but if this file is
line by line then couldn't you just read each line into a cell in an
array? Then you could just pick the cells you need to read into your
DB columns? I think that would be the easiest if the file is
segregated into lines like you describe.

HTH

V
When you load a textfile in C#, you get access to a ReadLine() method.

There's no rocket science here.
You need to ReadLine, and look for things you can bank on.

using System;
using System.IO;

class Test
{
public static void Main()
{
try
{ bool isANewCar = false; int lineRowPerSingleCar = 0;
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
lineRowPerSingleCar +=1; if
(line.Substring(0,10).ToUpper() == "DEALERSHIP"{ // figure out a way
to get the last characters, perhaps on the ":" isANewCar =
true;lineRowPerSingleCar = 0; //reset} switch
(lineRowPerSingleCar){ case 2: case 3: case 4: //do
nothing break; default: // do somehting else break;}
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

It's ugly as sin, but that's how you read files, where the format is a
little whack.
Looking at it, I'd use "Dealership number" to signal a new car. And reset
the lineCounter based on that.
Ignore 2, 3, 4, and do something with the rest.

Perhaps the sample above can get you going.


"CsharpGuy" <CsharpGuy@.discussions.microsoft.com> wrote in message
news:223A48D2-C00A-41D9-86D6-A8D5A0F88948@.microsoft.com...
> I have to read a text file and parse it out to load to a db and I'm having
> some issues in doing it. here is what the text file looks like
>
> Dealership number: 98665362236
> Location: Maryland
> Owner: John Smith
> Type: Luxury
> BMW, 325i, VIN12363625252362, New,, 20051212. 35400, Ocoonner
> Lexus, IS300, VIN6936363633363. Used, Small dent on driver side, 20050112,
> 24000, JSmith
> I need to account the Dealership number
> then get the other information starting with BMW, how can I skip line 2
thru
> 4 and still get teh dealership number and the lines starting with BMW?
> so the file is
> Make, Model, VIN#, New/Used, any details, date sold,. price and salesmen

Text file upload

Does anyone know of any sample code out there that allows a simple text file to be uplaoded and then stored in a SQL2005 database?

I have a system to record reports and it would be great to be able to upload and store the reports in the database and then be able to display them again via a web page linked from the record concerned.

regards

for saving a file in the database ... you have to convert it in the Binary array and save it as Binary.

On other hand ... better idea will be ... which i would do in your case ... save just the Text of the file in your Database ... make extra columns for the file meta data contents ... like ... name ... extension .. when it was created ... eidted.

then you will have more room in your database ... and ... processing in both directions will be alot faster...


Why can't you just save the filename in the database and store the actual file in another directory? That way, if you want to display it on a webpage, you can provide a link to the actual file. It would save a lot more time to do it this way then to go through the trouble of saving the document in a database table.

(In my html)
Upload Attachment:

<asp:FileUpload ID="FileUpload1" runat="server" Height="20" Width="300" BorderColor="#BFBFBE"> File Types: (.doc, .pdf, .rtf, .txt, .xls).pdf, .rtf, .txt, .xls)


(In my code behind)
if (FileUpload1.HasFile) {string fileext = Path.GetExtension(FileUpload1.FileName).ToLower();//rtf, doc, pdf, txt, xlsif (fileext ==".doc" || fileext ==".rtf" || fileext ==".pdf" || fileext ==".txt" || fileext ==".xls") {string uniqueFileName = System.Guid.NewGuid().ToString(); HttpPostedFile hp = FileUpload1.PostedFile; hp.SaveAs(@.Request.ServerVariables["APPL_PHYSICAL_PATH"] +"uploads\\" + uniqueFileName.ToString() + fileext.ToString()); } }
Then call your method that will save the uploaded document to the database. This way, you know all documents will be in the uploads folder (and all files will have unique names). When you go to display this in an html page later on, you'll know the location and will just have to pull the filename from the database.

Why can't you just save the filename in the database and store the actual file in another directory? That way, if you want to display it on a webpage, you can provide a link to the actual file

Acutally i would also prefer this one.

Based on my understanding, I think there may be a performance issue if you store the uploaded file in a database. So, storing the meta-data of the file into a db and the file to a file server is a better solution. Also, if the file is too large in size, i would suggest using a activeX upload control.

thanks.


omerkamal:

On other hand ... better idea will be ... which i would do in your case ... save just the Text of the file in your Database ... make extra columns for the file meta data contents ... like ... name ... extension .. when it was created ... eidted.

then you will have more room in your database ... and ... processing in both directions will be alot faster...

i totally agree with omerkamal ; saving just Text of the file in database (if only textfile is tobe uploaded) would be a better idea for fast processing.,

Text file size limitation?

I have a program that writes records to a .TXT file.

The code seems to fail when the file reaches the 5mb mark.

Is this a limitation in ASP, or is it related to how much memory I have in the machine?

Thank you.how are you writing to the file?
if you are appending, it should not be a problem.
Well, here's a snippet...


fp = File.CreateText("c:\AccountFinal.txt")

...gather data from 50,000 accounts & other sources, etc here...

fp.WriteLine(BranchNo & AcctType & AcctNo & AcctTitle & totAddr & Phone & SSN & OwnType & SPACE(21) & ActTotals2 & SPACE(41))

fp.Close()

Is there an easier way to do this?

Thanks.
Does it throw an error? If so, what's the error.

Maybe your script times out because it takes to long?
No errors.

Just stops.

It goes through the first 12,000 records (~5mb), then stops.

I change the code to go through the next roughly 12,000 records (~5mb), and it stops again.

... and so on, until I get to the last record.

If I only go through any ~10,000 records, the program finishes normally. (has totals at the end)
Just a wild guess, but could this be related to the database access instead of the writing to file?

I remember from VB6 (a long time ago) that records got read into in blocks, and that you had to do .MoveLast .MoveFirst to get the total amount of records. Maybe there's still something like that, and that it goes wrong when it wants to read the next 'block'

Instead of writing to a file, try incrementing a variable once. If it goes above 12000 the problem is in the file writing, if it stops at 12000 I'm guessing database issue
You might be on to something there. (database issue)

I first changed the code to Append the records to the text file like this...

'Get Records from DBs, and do stuff to them...

fp = File.AppendText(FILENAME)
fp.WriteLine(BranchNo & AcctType & AcctNo & AcctTitle & totAddr & Phone & SSN & OwnType & SPACE(21) & ActTotals2 & SPACE(41))
fp.Close()

It still bombed out, around the same time the previous code did.

I tried your suggestion, and got the same results.

Any thoughts on where I should look next?

Thanks.
How are you getting your results? What database are you using?

I remember something vaguely from MySQL, there there was an option to determine the max size of the request sent back.

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you can actually transmit between the client and server is determined by the amount of available memory and the size of the communications buffers. You can change the message buffer size (max_allowed_packet), but you must do so on both the server and client ends. See section 7.5.2 Tuning Server Parameters.

http://www.mysql.com/doc/en/Server_parameters.html
max_allowed_packet current value: 1048576

I think this is the one. Don't know if your database has something similar, set to 5MB.
You will have to change the settings in web.config or machine.config file for the file size limit. 5 mb is the default limit set by web.config

Try adding the following lines in the <system.web
<httpRuntime executionTimeout="500" maxRequestLength="72000" /
72000 here refers to approximately 72 mb. change it to the limit you want to set and see if that works.
Access 2k is where all of the account info resides.

Basically, I open the table with the 50k records in a DS, and do a for...Next through the entire file. Do you think this can be part of the problem?

Here is the main routine... I didn't include all of the functions, they really just chain to other tables & grab phone#'s & such.


<%@. Import Namespace="System.IO" %>
<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.Data.OLEDB" %>
<%@. Page Language="VB" Debug="true" %
<script language="VB" Debug="True" runat="server"
Public strConn As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" & server.mappath("db2.mdb") &";"
Dim totAddr, AddressNumber, strPers, strOrg, lblStatus, fName, ActTotals2 as String
Dim myNewRow, totalCount, CKTot, JODTot, IRATot, INDTot, COATot, CSATot, SAVTot As Single
Dim x, fLen as Integer

Sub Page_Load(Src As Object, E As EventArgs)
Dim strSQL AS String = "Select * From Accounts2 Order BY AcctNbr"
Dim GetAcctsCommand As OleDbCommand = New OleDbCommand
Dim Connect as New OLEDBConnection(strConn)
GetAcctsCommand.Connection = Connect
Dim Adapter As New OleDBDataAdapter(strSQL, Connect)
Dim AccountsDS As DataSet = New DataSet
Dim RcdCount As Integer
Adapter.Fill(AccountsDS,"Accounts2")
RcdCount = AccountsDS.Tables("Accounts2").Rows.Count
Dim fp As StreamWriter
Dim AdrNbr, AcctNo, Phone, SSN, AcctType, BranchNo, OwnType, AcctTotal, AcctTitle, tmpField As String
Dim FILENAME as String = Server.MapPath("AccountFinal.txt")

Try
For x= 0 to RcdCount - 1
myNewRow = CType(AccountsDS.Tables("Accounts2").Rows(X).Item("BALAMT"), Single)
If myNewRow > 0 then
totalCount=totalcount + myNewRow
tmpField = AccountsDS.Tables("Accounts2").Rows(X).Item("BranchOrgNbr")
BranchNo = zFill(tmpField, 3)
tmpField = AccountsDS.Tables("Accounts2").Rows(X).Item("AcctNbr")
AcctNo = zFill(tmpField, 13)
AcctType = AccountsDS.Tables("Accounts2").Rows(X).Item("MJAcctTypCd") & SPACE(3-LEN(AccountsDS.Tables("Accounts2").Rows(X).Item("MJAcctTypCd")))
If AcctType = "CK " Then
AcctType = "40"
CKTot = CKTot + myNewRow
Else
AcctType = "10"
SAVTot = SAVTot + myNewRow
End If
OwnType = AccountsDS.Tables("Accounts2").Rows(X).Item("OwnCd") & SPACE(3-LEN(AccountsDS.Tables("Accounts2").Rows(X).Item("OwnCd")))
Select CASE OwnType
Case "JO ", "JA "
OwnType = "JOD"
JODTot = JODTot + myNewRow
Case "S "
If Left(AccountsDS.Tables("Accounts2").Rows(X).Item("CurrMiAcctTypCD"),1) = "R" Then
OwnType = "IRA"
IRATot = IRATot + myNewRow
Else
OwnType = "IND"
INDTot = INDTot + myNewRow
End If
Case "PUB"
OwnType = "COA"
COATot = COATot + myNewRow
End Select
If InStr(AcctTitle, "(Min") > 0 then
OwnType = "CSA"
CSATot = CSATot + myNewRow
End If

AcctTitle = GetTitle(AccountsDS.Tables("Accounts2").Rows(X).Item("AcctNbr"))
SSN = GetSSN(AccountsDS.Tables("Accounts2").Rows(X).Item("PERS_TAXID"), AccountsDS.Tables("Accounts2").Rows(X).Item("ORG_TAXID"))
Phone = GetPhone(AccountsDS.Tables("Accounts2").Rows(X).Item("TAXRPTFORPERSNBR"), AccountsDS.Tables("Accounts2").Rows(X).Item("TAXRPTFORORGNBR"))
If Phone = "" then Phone = Space(14)
AdrNbr = GetAddrNbr(AccountsDS.Tables("Accounts2").Rows(X).Item("TAXRPTFORPERSNBR"), AccountsDS.Tables("Accounts2").Rows(X).Item("TAXRPTFORORGNBR"))
totAddr = GetAddress(AdrNbr)
ActTotals2 = CType(Format(myNewRow,"0000000000.00"), String)
fp = File.AppendText(FILENAME)
fp.WriteLine(BranchNo & AcctType & AcctNo & AcctTitle & totAddr & Phone & SSN & OwnType & SPACE(21) & ActTotals2 & SPACE(41))
fp.Flush()
fp.Close()
lblStatus = "File Succesfully created!"
End If
Next
Catch err As Exception
lblStatus = "File Creation failed. Reason is as follows " & err.ToString()
Finally
End Try
End Sub


I tried all of the other suggestions, now I get this error:

File Creation failed. Reason is as follows System.IO.IOException: The process cannot access the file "c:\inetpub\wwwroot\AccountFinal.txt" because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String str) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) at System.IO.StreamWriter.CreateFile(String path, Boolean append) at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize) at System.IO.StreamWriter..ctor(String path, Boolean append) at System.IO.File.AppendText(String path) at ASP.Accountlist6_aspx.Page_Load(Object Src, EventArgs E) in c:\inetpub\wwwroot\accountlist6.aspx:line 76 DONE!

going to try this next...

"You will have to change the settings in web.config or machine.config file for the file size limit. 5 mb is the default limit set by web.config

Try adding the following lines in the <system.web
<httpRuntime executionTimeout="500" maxRequestLength="72000" /
72000 here refers to approximately 72 mb. change it to the limit you want to set and see if that works. "

I'll let you know what happens.

Thanks.
BTW, if I make the following change, will I need to re-start the web server?

<httpRuntime executionTimeout="500" maxRequestLength="72000" /
Thanks.
That's just a web.config change. You don't even have to recompile for that to take effect, just save it to the server.
Ok, made the last change, now I get this dreaded message:

The page cannot be displayed...

But it looks like the ASPNET_WS.exe process is still going?

Any thoughts on how to keep the page from timing out?

Thanks.
It has to go in the system.web like so


<configuration>
<appSettings>
<add key="connString" value="sss" />
</appSettings>
<system.web>
<httpRuntime maxRequestLength="100000" />
<compilation defaultLanguage="vb" debug="true"></compilation>

text files.......

Heya all,

I am not sure if this is in the right spot or not thou.

what I would like to do is to be able to read the contents of a text file from any domain

eg
if i specify www.mydomain.com/copyright.txt

how can i read the contents (including line breaks) into a variable in a script?

not that the copyright would not be on my server.

pwpaust
www.abyss.wswould xml be better for this?

because its kinda like a configuration file i guess.

pwpaust
www.abyss.ws

Saturday, March 24, 2012

text searching through html/.apx files in .net

I want to implement search engine that inputs from user then search all html or .aspx file and display results.
Kindly guide me how can i do this.
Any help/sample code will be appreciatedHi,
Take a look @.
-Creating Search Pages with Index Server and .NET

-WhatuSeek.com

HTH

Text to HTML

I have a text file perfectly formatted with carriage returns, indents,
spacing etc in NotePad. I want to put text that looks exactly like that
into a <div> and get it formatted exactly the same way in Visual Studio.
But I can't seem to get this done in Visual Studio other than pasting it
into a textbox - which I don't want to do.
If I paste it into a div in design view it removes all formatting. Same in
source view. If I put it into MS Word and save as plain html it puts all
sorts of gargage in it that doesn't work in VS.
Is there any program that will do this?
Thanks,
TPut the text into a <PRE>...</PRE> tag, which will hold on to the whitespace
formatting. You can put the PRE tag into a DIV tag if you want.
"Tina" <TinaMSeaburn@.nospamexcite.com> wrote in message
news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...
>I have a text file perfectly formatted with carriage returns, indents,
>spacing etc in NotePad. I want to put text that looks exactly like that
>into a <div> and get it formatted exactly the same way in Visual Studio.
>But I can't seem to get this done in Visual Studio other than pasting it
>into a textbox - which I don't want to do.
> If I paste it into a div in design view it removes all formatting. Same
> in source view. If I put it into MS Word and save as plain html it puts
> all sorts of gargage in it that doesn't work in VS.
> Is there any program that will do this?
> Thanks,
> T
>
Well, that works pretty good. Thanks.
Is there a way to get the text to wrap inside the PRE or the DIV?
Thanks,
T
"Scott M." <s-mar@.nospam.nospam> wrote in message
news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...
> Put the text into a <PRE>...</PRE> tag, which will hold on to the
> whitespace formatting. You can put the PRE tag into a DIV tag if you
> want.
>
> "Tina" <TinaMSeaburn@.nospamexcite.com> wrote in message
> news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...
>
Oh, I also notice that text inside the PRE will not follow CSS specified
fonts so it looks like
it acts just like text in a text box and these are the reasons I did not
want to use a textbox.
T
"Scott M." <s-mar@.nospam.nospam> wrote in message
news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...
> Put the text into a <PRE>...</PRE> tag, which will hold on to the
> whitespace formatting. You can put the PRE tag into a DIV tag if you
> want.
>
> "Tina" <TinaMSeaburn@.nospamexcite.com> wrote in message
> news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...
>
Sorry, you can't have it both ways. Use PRE and WYSIWYG, no more and no
less - don't use PRE and all white space is stripped.
"Tina" <TinaMSeaburn@.nospamexcite.com> wrote in message
news:OvyGZcO5GHA.3736@.TK2MSFTNGP02.phx.gbl...
> Well, that works pretty good. Thanks.
> Is there a way to get the text to wrap inside the PRE or the DIV?
> Thanks,
> T
> "Scott M." <s-mar@.nospam.nospam> wrote in message
> news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...
>
Again, that's what PRE does - uses a monospaced font.
You've got to remember the language you are working in. HTML is a language
where whitespace stripping occurs. If you want to build space back in, you
could look into entities such as (which will get messy). You could
read your text file and parse that file into <P>, <BR> and where you
read line breaks and spaces.
"Tina" <TinaMSeaburn@.nospamexcite.com> wrote in message
news:eqS$4fO5GHA.1248@.TK2MSFTNGP03.phx.gbl...
> Oh, I also notice that text inside the PRE will not follow CSS specified
> fonts so it looks like
> it acts just like text in a text box and these are the reasons I did not
> want to use a textbox.
> T
> "Scott M." <s-mar@.nospam.nospam> wrote in message
> news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...
>
PRE
{
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
Tina wrote:
> Well, that works pretty good. Thanks.
> Is there a way to get the text to wrap inside the PRE or the DIV?
> Thanks,
> T
> "Scott M." <s-mar@.nospam.nospam> wrote in message
> news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...

Text to HTML

I have a text file perfectly formatted with carriage returns, indents,
spacing etc in NotePad. I want to put text that looks exactly like that
into a <divand get it formatted exactly the same way in Visual Studio.
But I can't seem to get this done in Visual Studio other than pasting it
into a textbox - which I don't want to do.

If I paste it into a div in design view it removes all formatting. Same in
source view. If I put it into MS Word and save as plain html it puts all
sorts of gargage in it that doesn't work in VS.

Is there any program that will do this?

Thanks,
TPut the text into a <PRE>...</PREtag, which will hold on to the whitespace
formatting. You can put the PRE tag into a DIV tag if you want.

"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>I have a text file perfectly formatted with carriage returns, indents,
>spacing etc in NotePad. I want to put text that looks exactly like that
>into a <divand get it formatted exactly the same way in Visual Studio.
>But I can't seem to get this done in Visual Studio other than pasting it
>into a textbox - which I don't want to do.
>
If I paste it into a div in design view it removes all formatting. Same
in source view. If I put it into MS Word and save as plain html it puts
all sorts of gargage in it that doesn't work in VS.
>
Is there any program that will do this?
>
Thanks,
T
>


Well, that works pretty good. Thanks.
Is there a way to get the text to wrap inside the PRE or the DIV?
Thanks,
T

"Scott M." <s-mar@.nospam.nospamwrote in message
news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

Put the text into a <PRE>...</PREtag, which will hold on to the
whitespace formatting. You can put the PRE tag into a DIV tag if you
want.
>
>
"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>>I have a text file perfectly formatted with carriage returns, indents,
>>spacing etc in NotePad. I want to put text that looks exactly like that
>>into a <divand get it formatted exactly the same way in Visual Studio.
>>But I can't seem to get this done in Visual Studio other than pasting it
>>into a textbox - which I don't want to do.
>>
>If I paste it into a div in design view it removes all formatting. Same
>in source view. If I put it into MS Word and save as plain html it puts
>all sorts of gargage in it that doesn't work in VS.
>>
>Is there any program that will do this?
>>
>Thanks,
>T
>>


>
>


Oh, I also notice that text inside the PRE will not follow CSS specified
fonts so it looks like
it acts just like text in a text box and these are the reasons I did not
want to use a textbox.
T

"Scott M." <s-mar@.nospam.nospamwrote in message
news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

Put the text into a <PRE>...</PREtag, which will hold on to the
whitespace formatting. You can put the PRE tag into a DIV tag if you
want.
>
>
"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>>I have a text file perfectly formatted with carriage returns, indents,
>>spacing etc in NotePad. I want to put text that looks exactly like that
>>into a <divand get it formatted exactly the same way in Visual Studio.
>>But I can't seem to get this done in Visual Studio other than pasting it
>>into a textbox - which I don't want to do.
>>
>If I paste it into a div in design view it removes all formatting. Same
>in source view. If I put it into MS Word and save as plain html it puts
>all sorts of gargage in it that doesn't work in VS.
>>
>Is there any program that will do this?
>>
>Thanks,
>T
>>


>
>


Sorry, you can't have it both ways. Use PRE and WYSIWYG, no more and no
less - don't use PRE and all white space is stripped.

"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
news:OvyGZcO5GHA.3736@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

Well, that works pretty good. Thanks.
Is there a way to get the text to wrap inside the PRE or the DIV?
Thanks,
T
>
"Scott M." <s-mar@.nospam.nospamwrote in message
news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>Put the text into a <PRE>...</PREtag, which will hold on to the
>whitespace formatting. You can put the PRE tag into a DIV tag if you
>want.
>>
>>
>"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
>news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>>>I have a text file perfectly formatted with carriage returns, indents,
>>>spacing etc in NotePad. I want to put text that looks exactly like that
>>>into a <divand get it formatted exactly the same way in Visual Studio.
>>>But I can't seem to get this done in Visual Studio other than pasting it
>>>into a textbox - which I don't want to do.
>>>
>>If I paste it into a div in design view it removes all formatting. Same
>>in source view. If I put it into MS Word and save as plain html it puts
>>all sorts of gargage in it that doesn't work in VS.
>>>
>>Is there any program that will do this?
>>>
>>Thanks,
>>T
>>>


>>
>>


>
>


Again, that's what PRE does - uses a monospaced font.

You've got to remember the language you are working in. HTML is a language
where whitespace stripping occurs. If you want to build space back in, you
could look into entities such as (which will get messy). You could
read your text file and parse that file into <P>, <BR and where you
read line breaks and spaces.

"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
news:eqS$4fO5GHA.1248@.TK2MSFTNGP03.phx.gbl...

Quote:

Originally Posted by

Oh, I also notice that text inside the PRE will not follow CSS specified
fonts so it looks like
it acts just like text in a text box and these are the reasons I did not
want to use a textbox.
T
>
"Scott M." <s-mar@.nospam.nospamwrote in message
news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>Put the text into a <PRE>...</PREtag, which will hold on to the
>whitespace formatting. You can put the PRE tag into a DIV tag if you
>want.
>>
>>
>"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
>news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>>>I have a text file perfectly formatted with carriage returns, indents,
>>>spacing etc in NotePad. I want to put text that looks exactly like that
>>>into a <divand get it formatted exactly the same way in Visual Studio.
>>>But I can't seem to get this done in Visual Studio other than pasting it
>>>into a textbox - which I don't want to do.
>>>
>>If I paste it into a div in design view it removes all formatting. Same
>>in source view. If I put it into MS Word and save as plain html it puts
>>all sorts of gargage in it that doesn't work in VS.
>>>
>>Is there any program that will do this?
>>>
>>Thanks,
>>T
>>>


>>
>>


>
>


PRE
{
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}

Tina wrote:

Quote:

Originally Posted by

Well, that works pretty good. Thanks.
Is there a way to get the text to wrap inside the PRE or the DIV?
Thanks,
T
>
"Scott M." <s-mar@.nospam.nospamwrote in message
news:ulx$s1L5GHA.3452@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

Put the text into a <PRE>...</PREtag, which will hold on to the
whitespace formatting. You can put the PRE tag into a DIV tag if you
want.

"Tina" <TinaMSeaburn@.nospamexcite.comwrote in message
news:OLc94tL5GHA.3376@.TK2MSFTNGP05.phx.gbl...

Quote:

Originally Posted by

>I have a text file perfectly formatted with carriage returns, indents,
>spacing etc in NotePad. I want to put text that looks exactly like that
>into a <divand get it formatted exactly the same way in Visual Studio.
>But I can't seem to get this done in Visual Studio other than pasting it
>into a textbox - which I don't want to do.
>
If I paste it into a div in design view it removes all formatting. Same
in source view. If I put it into MS Word and save as plain html it puts
all sorts of gargage in it that doesn't work in VS.
>
Is there any program that will do this?
>
Thanks,
T
>


Thursday, March 22, 2012

Text written to StreamWriter disappears when it is closed

Hi, I wrote my own logger class to log any errors in my program to a file. The idea is simply to provide a wrapper for the TextWriter or StreamWriter class that adds the ability to write strings, exceptions and to move the file. However when I run a very simple test program, closing the stream erases the contents of the file. My code is below:

First the class:

public class Logger
{
private System.IO.StreamtWriter sw_log;
private string log_path;

public Logger(string fpath,bool append)
{
GIM.Utility.ensure_path_exists(fpath);
sw_log =new System.IO.StreamWriter(fpath, append);
log_path = fpath;
}

public void Log(string s)
{
GIM.Utility.ensure_path_exists(log_path);
sw_log.WriteLine(s);
}

public void Log(Exception e)
{
if(e.InnerException !=null)
Log(e.InnerException);
Log("Error: "+e.Message);
}

public void MoveFile(string destination_path)
{
sw_log.Close();
System.IO.File.Move(log_path, destination_path);
sw_log =new System.IO.StreamWriter(destination_path,true);
log_path = destination_path;
}

public string GetLogContents()
{
sw_log.Close();

string s = String.Empty;
System.IO.StreamReader sr =new System.IO.StreamReader(log_path);
s = sr.ReadToEnd();
sr.Close();

sw_log =new System.IO.StreamWriter(log_path);
return s;
}

public void Close() {sw_log.Close();}


Now the test program:

using System;
namespace LoggerTest
{
class Class1
{

[STAThread]
static void Main(string[] args)
{
string path ="C:\\test\\other_deployment.log";
Logger L =new Logger(path,true);
L.Log("test test test");
L.Close();

Console.WriteLine(L.GetLogContents());
L.Close();
Console.ReadLine();

Console.WriteLine("----------");
System.IO.StreamReader sr =new System.IO.StreamReader(path);
Console.WriteLine(sr.ReadToEnd());
sr.Close();
Console.ReadLine();
}
}
}

The result is:

test test test

--------

(blank line because nothing is read in)

And an empty file

Does anyone have any idea what might be going on?

Try calling .Flush() before you close the stream.


I would suggest that you simplify the process. Write to the log file and see if that works. Then read from the log file. Then when both are working try moving the file.

Better yet, write the log file to where you want it and don't waste time with the move.

Your code looks overly complicated and you are opening and closing the file rather frequently. Is that really needed?

Personally I use:

Public sLogasString

Public wAs StreamWriter = File.AppendText("C:\path\error.log")

sLog = ControlChars.CrLf &"Started: " & Now

sLog = sLog & ControlChars.CrLf &"###################"

'add details as needed

sLog = sLog & ControlChars.CrLf &"Ended: " & Now

sLog = sLog & ControlChars.CrLf &"###################"

w.Write(sLog)

w.Flush

w.Close

w =Nothing

and it works fine.


rewrote the close method as:

public void Close() {sw_log.Flush();sw_log.Close();}

Still getting the same result


kraznodar,

I had something to that extent before, I just had a simple function doing logging and it worked. However it has become prudent to move the logging responsibilities to a separate object since I am now writing to multiple logs and specifically because I would like to keep from opening and closing the file too much.

If you look at the code in the Logger class it actually opens and closes the file only when absolutely necessary (when opening it the first time, when close is called, and when moving)


First of all, why do you not have a "new" sub? Instead of a sub called logger try calling it new so it complies with OOP standards.


Comment out the move and see if the file is still empty.


No clue what you're talking about, please explain. Are you confused about why I do not have the keyword 'sub' in there anywhere? It is because this is c# not vb


What the hell are you talking about? The move never runs, I don't call it at any point.


kraznodar:

First of all, why do you not have a "new" sub? Instead of a sub called logger try calling it new so it complies with OOP standards.

I don't make sense here! Ignore that post.


Are you actually going into "My Computer" and manually opening the file to check it's content? If not, then try that and see if the file is actually empty or if it has content but isn't reading correctly. I think I'm not helping here so hopefully a C# person can step in and do a better job. Sorry I'm not more benefit to you.


Yes, the file is actually empty, 0 bytes and opening it in notepad shows it being empty. I feel like this might be a matter of using the wrong keyword in instantiating the sw_log variable?


Umm...bump.

Lots of posts, no solution


Here is a logger that I wrote. I am not sure what it wrong with yours, but it does do everything that yours should do. The difference is it uses the same stream for reading / writing, and it supports a couple of other operations. It also implements IDisposable:

1public class Logger : IDisposable2{3public const string DEFAULT_LOG_PATH = @."C:\logs\mylog.log";4private readonly string _logPath;5private readonly bool _append;6private readonly OpenBehavior _openBehavior;7const int BUFFER_SIZE = 0x1000;8private FileStream _writer;9private readonly byte[] _newLine;10private bool _hasWrittenOnce =false;1112public Logger(string logPath,bool append, OpenBehavior openBehavior)13{14_newLine = Encoding.Default.GetBytes(Environment.NewLine);15_logPath = logPath;16_append = append;17_openBehavior = openBehavior;18InitialFileSystem();19InitializeStream();20}212223public Logger(bool append)24:this(DEFAULT_LOG_PATH, append, OpenBehavior.AutoCreate)25{ }2627public Logger(OpenBehavior openBehavior)28:this(DEFAULT_LOG_PATH,true, openBehavior)29{ }3031public Logger()32:this(true)33{ }3435private void InitialFileSystem()36{37string directory =new FileInfo(_logPath).Directory.FullName;38bool doesPathExist = Directory.Exists(directory);39bool doesFileExist = File.Exists(_logPath);40if (!doesPathExist || !doesFileExist)41{42if (_openBehavior == OpenBehavior.ThrowIfDoesNotExist)43throw new Exception("The logging file \"" + _logPath + "does not exist.");44if (!doesPathExist)45Directory.CreateDirectory(directory);46}47}4849private void InitializeStream()50{51_writer =new FileStream(_logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, BUFFER_SIZE, FileOptions.WriteThrough);52}5354private void WriteLine(string line)55{56if (!_hasWrittenOnce && !_append)57{58_writer.SetLength(0);59}60else if (!_hasWrittenOnce && _append)61{62_writer.Position = _writer.Length;63}64int dataLength = Encoding.Default.GetByteCount(line);65byte[] data =new byte[dataLength + _newLine.Length];66Buffer.BlockCopy(Encoding.Default.GetBytes(line), 0, data, 0, dataLength);67Buffer.BlockCopy(_newLine,0,data,dataLength,_newLine.Length);68_writer.Write(data, 0, data.Length);69_hasWrittenOnce =true;70}7172public void Log(string message)73{74WriteLine(message);75}7677public void Log(Exception exception)78{79if (exception.InnerException !=null)80Log(exception.InnerException);81Log(exception.Message);82}8384public void MoveLog(string newPath)85{86if(!Directory.Exists(newPath))87Directory.CreateDirectory(newPath);88string fileName = Path.GetFileName(_logPath);89string newPathWithFile = Path.Combine(newPath, fileName);90_writer.Flush();91_writer.Dispose();92File.Move(_logPath, newPathWithFile);93_writer =new FileStream(newPathWithFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, BUFFER_SIZE, FileOptions.WriteThrough);94}9596public string ReadLog()97{98StringBuilder log =new StringBuilder((int)_writer.Length);99long previousPos = _writer.Position;100_writer.Position = 0;101int bytesRead;102byte[] buffer =new byte[BUFFER_SIZE];103while ((bytesRead = _writer.Read(buffer, 0, BUFFER_SIZE)) != 0)104{105string data = Encoding.Default.GetString(buffer,0, bytesRead);106log.Append(data);107}108_writer.Position = previousPos;109return log.ToString();110}111112public void TruncateLog()113{114_writer.SetLength(0L);115}116117public void CopyLogToStream(Stream stream)118{119long previousPos = _writer.Position;120_writer.Position = 0;121BlockCopy(_writer, stream);122_writer.Position = previousPos;123}124125private void BlockCopy(Stream input, Stream output)126{127byte[] buffer =new byte[BUFFER_SIZE];128int bytesRead;129while ((bytesRead = input.Read(buffer, 0, BUFFER_SIZE)) != 0)130{131output.Write(buffer, 0, bytesRead);132output.Flush();133}134}135136public void Dispose()137{138_writer.Flush();139_writer.Dispose();140GC.WaitForPendingFinalizers();141GC.SuppressFinalize(this);142}143144~Logger()145{146Dispose();147}148}149150public enum OpenBehavior151{152ThrowIfDoesNotExist,153AutoCreate154}

You would use it like this:

static void Main(){using (Logger logger =new Logger()){try{logger.Log("Log message!");throw new Exception("TEST Exception");}catch (Exception e){logger.Log(e);}logger.CopyLogToStream(Console.OpenStandardOutput());Console.WriteLine(new string('-', Console.BufferWidth-1));Console.Write(logger.ReadLog());Console.ReadKey(true);}}

Today,I just registered.
But I hnow a little English.
I hope everyone can help me more.
hard study and study with you.