hi guys
what i need to do is to copy a portion of text from one txt file to another txt file
for eg :
if there is a word called <body> in the txt file it has to search till '<body>' is found and copy the subsequent text till the next specified word ie '</body>' in that file
to another file on the disk
i was using the streamreader and writer for this but so far i havent been able to do it
pls help
![]() |
0 |
![]() |
Hi Kuruvilla,
I have written a completely sample to demostrate how you can do that, please check the code snippet below.
//File: Default3.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;public partial class Default3 : System.Web.UI.Page
{
private string file_content = "";
protected void Page_Load(object sender, EventArgs e)
{
string path = Server.MapPath("./") + "HTMLPage.htm";
string content = "";
if (ReadTextFile(path))
if (Extract_file(ref content))
WriteTextFile(@"C:\testwrite.txt",content);
}private bool ReadTextFile(string filename)
{
StreamReader TxtSR;
try
{
if (File.Exists(filename))
{
TxtSR = File.OpenText(filename);
file_content = TxtSR.ReadToEnd();
TxtSR.Close();
}
}
catch (Exception)
{
return false;
}
return true;
}private bool Extract_file(ref string content)
{
string tmp = file_content.ToLower();
int idx = 0;
int idx2 = 0;
idx = tmp.IndexOf("<body>");
if (-1 == idx) return false;
idx2 = tmp.IndexOf("</body>", idx);
if (-1 == idx2) return false;
idx2 += 7;
content = tmp.Substring(idx, idx2-idx);
return true;
}private bool WriteTextFile(string filename,string content)
{
StreamWriter TxtSW;
try
{
TxtSW = File.CreateText(filename);
TxtSW.Write(content);
TxtSW.Flush();
TxtSW.Close();
}
catch (Exception)
{
return false;
}return true;
}
}Regards,
Xun
Regards,
Xun Ye.
Microsoft Online Community Support
Please remember to click “Mark as Answer” on the post that
helps you, and to click “Unmark as Answer” if a marked post
does not actually answer your question. This can be beneficial
to other community members reading the thread.
![]() |
0 |
![]() |
thanks Xun Ye that snippet really helped!
![]() |
0 |
![]() |