copy specified content from one file to another file

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
Kuruvilla
12/26/2007 6:09:51 AM
asp.net.web-forms 93655 articles. 6 followers. Follow

2 Replies
801 Views

Similar Articles

[PageSpeed] 43
Get it on Google Play
Get it on Apple App Store

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
Xun
12/28/2007 3:02:45 AM

thanks  Xun  Ye that snippet really helped! 

0
Kuruvilla
12/28/2007 6:48:53 AM
Reply:

Similar Artilces:

File.Copy and File.CopyTo DO NOT COPY CONTENTS OF FILE!@
I posted on here before but no one has been of any help. I am trying to copy files of type .zip .jpg and .pdf from ones folder to another (I dont want to move it, just make a copy). How can I do this? When I use File.Copy and File.CopyTo it makes a new file in the right folder but has no content and it also erases the content on the orignal file. WTF? This is really making me mad. Visit VistaForums.com #1 Windows Vista Forum Here you go --->  http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=207Regards, Narayana Rao Surapaneni Architect | Author | MCSD for .NET | MCSD | SCJP ww...

Copying more than one file using File::Copy
Good day=3B I apologize in advance if this is a very stupid question=85 I=27m trying to concatenate two files and have the results written to a = third file=2E = Maybe I=27m missing something obvious=2E=2E=2E but in Perldoc for File=3A= =3ACopy I = read=3A =22The copy function takes two parameters=3A a file to copy from = and = a file to copy to=2E=22 What can I do if I have a second file I want to copy from=3F (i=2Ee=2E Li= ke = DOS copy command=3A c=3A=5C file1=2Etxt + file2=2Etxt file3=2Etxt will co= py the = contents of file1=2Etxt =26 file2=2Etxt and put the...

How to copy one existing excel file contents to a new excel file?
Hi All,    I need VB code to copy sheet contents of one exisiting excel file to another new excel file.   For example: I have abc.xls file with sheet name abcd.   I want to copy the contents to xyz sheet of new excel file xyz.xls. Pls help me regarding this. Regards Abdul      Pls help me.        Which version of Excel are you using? The latest uses an XML format which can be manipulated programatically. Don't forget to click "Mark as Answer" on the post that helped you.This credits that member, ear...

copy the which is before ",(comma)" in one file and matching pattern in another file
Problem Def: copy the pattern which before ",(comma)" and find a matching pattern in another file. status: i wrote following code. but it is not working properly. plz help me. #! C:\Perl\bin\perl.exe print "hello\n"; print "Please Enter Input File name(Give the complete path):"; $infile=<STDIN>; #give the input file name here chomp($infile); open ($in, "<", $infile) or die "Cannot open file for reading\n"; #Check whether the file can be opened for reading while (<$in>) { if(/,/) {print "before match:...

How can i copy file from one directory to another in vb.net?
Thank. Hi, use the File.Copy(sourcefile, destinationfilename) from the System.IO namespace. Taken from MSDN: Imports SystemImports System.IO Public Class Test    Public Shared Sub Main()        ' Specify the directories you want to manipulate.        Dim path As String = "c:\temp\MyTest.txt"        Dim path2 As String = path + "temp"         Try           ...

Create One File From Another File
Hoping to get suggestions on how to create a program that will read one file and create another file. The program has to read a Sybase SQLA DDL file and create certain elements of an Oracle DDL file. Specifically, the program would need to search the file 'resq.sql' for all instances of AUTOINCREMENT. On finding an instance of AUTOINCREMENT, the program would move some text from resq.sql into a... buffer? and create in the buffer an Oracle Sequence and ON INSERT TRIGGER statement. Once all instances of AUTOINCREMENT have a corresponding Sequence and Trigger statements, ...

Create One File From Another File
I posted an earlier question asking for approaches to creating one file from another. The status of this project is that the program will now take a Sybase SQL Anywhere DDL and create a corresponding file of Oracle Sequences and Triggers. Basically, for every instance of AUTOINCREMENT in the SQLA DDL, a Sequence and Before Insert Trigger is created in another file. The only problem with this potentially very useful program is the incredibly long time it takes to process our 300K SQLA DDL file. I think a sol'n may lie in my ability to sequentially read the DDL one character ...

IIS + .NET 3.5 Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. The system cannot find the file specified.
 Ok folks I need some help here. I have MS Server 2003 with IIS installed. Frameworks 2.0, 3.0 & 3.5 installed. The server has VS 2008 Web Developer installed because I am developing on it remotely. When I run the web site from inside VS everything is fine. I created a new website in IIS (named Intranet) and set it to run on Framework 2.0 and set the path to the root folder of the site (D:\Intranet). I also confirmed that VS was building for framework 3.5. When I open Internet Explorer on the server and go to http://localhost/Intranet I get the following error: "Could not ...

Error 1 Could not load file or assembly 'Microsoft.Web.Preview' or one of its dependencies. The system cannot find the file specified.
Trying to run the samples and this is the error I get.  After looking around I see others have gotten this error but with the beta versions.  My install is not a beta release and I have not had any of the betas installed.  Any ideas? I would look to your web config file or possibly your machine config file.   Im betting you somehow got some old beta settings in it.  possibly do a search for Microsoft.Web.Preview in your entire solution. AjaxButter The other thing i just noticed is you said you were running the samples. Im betting your usin...

Parser Error Message: Could not load file or assembly 'Microsoft.Web.Atlas' or one of its dependencies. The system cannot find the file specified.
hi all,I have a not so nice error that I can't solve. I use asp .net 2.0 and Atlas. The site works in dev but not on my server... I hope someone can help me out. RegardsStijnParser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not load file or assembly 'Microsoft.Web.Atlas' or one of its dependencies. The system cannot find the file specified.Source Error: Line 1: <...

Microsoft Chart control for .NET Framework about state management and serialization problem, it works OK with one XML file but fails with another XML file
I use Microsoft Chart control for .NET Framework , you can see details at http://blogs.msdn.com/alexgor/archive/2008/10/27/microsoft-chart-control-for-net-framework-released.aspx The Chart1 is load data from a xml and save to ViewStateData, so even if after I click Reload button, the chart1 still display OK! I'm very strange that the chart1 works well after click Reload button if it's loaded from Chart1.Serializer.Load(HttpContext.Current.Server.MapPath("~/Template/1.xml"));but chart1 don't display fter click Reload button if it's loaded from Chart1.Serializer.Loa...

one application has many web.config files which web.config file execute first?
hi to all In my application i will add three web.config file which will execute first. how to set it. Give me a guidlines. by Devan.G Hi,You can't add multiple web.config to applicationYou can add single web.config to each folder present in sub directories of your applicationYou can override the web.config files using multiple config files.SatalajWatch The true story of internet ||Yet another forum |||I'm big fan of Open source flash chart for .net very very simple I n t e r v i e w T i p s Hi, You can check this reference: http://www.beansoftware.com/ASP.NET-Tutorials/Mult...

Could not load file or assembly 'CrystalDecisions.Web, Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.
Hi,  Ima using Crystal Reports for Visual Studio .NET 2005 Could not load file or assembly 'CrystalDecisions.Web, Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.I am getting this error after I deploy the application. Then I installed Crystal Reports for Visual Studio .NET 2005 - Service Pack 1 (Updated Nov. 2007) Merge Modules for Crystal Reports for Visual Studio .NET 2005 This file contains the latest merge modules required for deploying .NET applications using Crystal Reports ...

Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified
I have downloaded the Ajax Control Toolkit Website Project. I want to run on Visual Studio 2005. But when I run the project I got the error like  Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified . </system.web>     <httpModules>        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neu...

Web resources about - copy specified content from one file to another file - asp.net.web-forms

With 4th-gen Uconnect, Fiat Chrysler embraces CarPlay and Android Auto
LAS VEGAS — Yet another automaker has brought both Apple CarPlay and Android Auto into its dashboards. This time, it's Fiat Chrysler Automobiles ...

Facebook's Zuckerberg is taking it on the run
Social network's CEO plans to do a lot of running this year, and he wants you to join in.

Saudi Arabia, Our Great and Good Ally
So what's happening in Saudi Arabia these days? Basically this: Saudi Arabia and Iran have been in a Cold War ever since the Iranian Revolution ...

Asian markets see renewed volatility in early trade
Hong Kong (AFP) - Asian markets witnessed fresh volatility Tuesday, a day after a global rout that saw trading suspended in Chinese markets, ...

Nokia's €15.6B public exchange offer for Alcatel-Lucent successful, French regulator says, companies ...
Katie Collins / CNET : Nokia's €15.6B public exchange offer for Alcatel-Lucent successful, French regulator says, companies to start merging ...

China police on lookout for suspected arsonist in deadly bus fire
NDTV China police on lookout for suspected arsonist in deadly bus fire Reuters BEIJING Chinese police have launched a manhunt for an arsonist ...

Backroad Anthem Posts Tribute to Craig Strickland: 'Today We Lost Our Brother'
People Magazine Backroad Anthem Posts Tribute to Craig Strickland: 'Today We Lost Our Brother' People Magazine Backroad Anthem has issued ...

Republicans Propose Volkswagen Bailout Right After the U.S. Government Sues Over Emissions Lies
The second-largest auto company in the world was sued by the U.S. Justice Department after it allegedly violated the Clean Air Act by installing ...

‘Pardon Steven Avery’ Petition Update & ‘Making A Murderer’ Follow-Up - UPROXX
"Pardon Steven Avery" petitions have received 200,000+ signatures, plus, your "Making A Murderer" follow-up story round up.

Christie and Rubio Try to Take Down Trump, Indirectly
Ten miles apart on a frigid Monday in New Hampshire, two leading rivals each pitched themselves as the toughest on terror. But their true common ...

Resources last updated: 1/5/2016 8:13:50 AM