Create a DIV Tag using ASP.NET with C#

Hi Friends 
Here is the Code to create div through C# . 
 
 
System.Web.UI.HtmlControls.HtmlGenericControl newDiv =
        new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
    newDiv.ID = "newDiv";
    newDiv.Style.Add(HtmlTextWriterStyle.Height, "20px");
    newDiv.Style.Add(HtmlTextWriterStyle.Width, "300px");
 
    tbl.Controls.Add(dynDiv);

0 comments:

How to Merge two DataTable and Get a Distinct Records from the Table using C#

Hi
     suppose we have two datatables dt1and dt2 first i marge both the datatables and then get the distinct records

  dt1 have some data &dt2 have some data now marge dt2 in dt1

                  dt1.Merge(dt2 ); //Here we marge the datatables

                  dt1.GetChanges();// Get Changes

Now we find the Distinct records of DataTable dt1

  dt1= dt1.DefaultView.ToTable(true, cols); //DedaultView return the Distinct record but before that we have to pass datatable column Array (cols) to this method. here cols us a array if column if Datatable.

hope this will help You

Regard,
Rajesh

0 comments:

How to get value from dynamic created Textbox using Params in C#

Hi friend .
  If we create dynamic Textbox in Asp.Net and Add it on the Place Holder like this,


public partial class _Default : System.Web.UI.Page
{
    string txtId;
    TextBox txt = new TextBox();
    protected void Page_Load(object sender, EventArgs e)
    {
       
        txt.ID = "txt";
        PlaceHolder1.Controls.Add(txt);
        txtId = txt.UniqueID; // this will give u Unique ID like this "ctl00$ContentPlaceHolder1$txt"
        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = Request.Params[txtId].ToString();
        
    }
}

Hope this will help you.
Rajesh

0 comments:

The difference between ID, ClientID and UniqueID


I this post I will try to explain the difference between those three commonly used properties. Each property is described in a separate section. Attached you can find a sample web site as well as two screenshots visually depicting the difference between the ID, ClientID and UniqueID properties.



ID

The ID property is used to assign an identifier to an ASP.NET server control which can be later used to access that control. You can use either the field generated in the codebehind or pass the value of the ID property to the FindControl method. There is a catch though - the ID property is unique only within the current NamingContainer (page, user control, control with item template etc). If a server control is defined inside the item template of some other control (Repeater, DataGrid) or user control, its ID property is no longer unique. For example, you can add some user control twice in the same page. Any child controls of that user control will have the same ID.  Also the ASP.NET page parser won't generate a codebehind field corresponding to the control ID in case the control is defined inside a template. This is the reason you cannot easily find a specific control when it is part of a template - you need to use the FindControl method of its container control instead. As a side note, setting the ID property is not mandatory. If you don't set it the ASP.NET Runtime will generate one for you in the form of "_ctl0", "_ctl1", etc.

UniqueID

The UniqueID property is the page-wide unique identifier of an ASP.NET server control. Its uniqueness is guaranteed by prefixing the ID of a server control with the ID of its NamingContainer. If the NamingContainer is the Page the UniqueID will remain the same as the ID.
For example if a Label with ID="Label1" is defined in a user control with ID = "UserControl1" the UniqueID of the Label will be "UserControl1$Label1". Adding another instance of the same user control (with ID = "UserControl2") will make the UniqueID of its child label to be "UserControl2$Label1".

The UniqueID property is also used to provide value for the HTML "name" attribute of input fields (checkboxes, dropdown lists, and hidden fields). UniqueID also plays major role in postbacks. The UniqueID property of a server control, which supports postbacks, provides data for the __EVENTTARGET hidden field. The ASP.NET Runtime then uses the __EVENTTARGET field to find the control which triggered the postback and then calls its RaisePostBackEvent method. Here is some code which illustrates the idea:

IPostBackEventHandler postBackInitiator =

Page.FindControl(Request.Form["__EVENTTARGET") As IPostBackEventHandler;

if (postBackInitiator != null)
    postBackInitiator.RaisePostBackEvent(Request.Form["__EVENTARGUMENT"]);

You can use the UniqueID property to find any control no matter how deep it is nested in the control hierarchy. Just pass its value to the FindControl method of the Page.
 

ClientID

The ClientID property is quite similar to the UniqueID. It is generated following the same rules (the ID of the control prefixed by the ID of its NamingContainer). The only difference is the separator - for the ClientID it is the "_" (underscore) symbol.
The ClientID property is globally unique among all controls defined in an ASP.NET page. You may ask why we need two different globally unique properties. The answer is that ClientID serves a different purpose than UniqueID. In most server controls the ClientID property provides the value for the HTML "id" attribute of the HTML tag of that server control. For example this:

<asp:Label ID="Label1" Text="Label" />
will render as this:
<span id="Label1">Label</span>

That's why you often use the following JavaScript statement to access the DOM element corresponding to some ASP.NET server control:

var label = document.getElementById("<%= Label1.ClientID%>");

which in turn renders as:

var label = document.getElementById("Label1");

It is worth mentioning that the values of the ID, UniqueID and ClientID will be the same if the control is defined in the master page (or the page). This however can often lead to unexpected errors. If the ID of the control is hardcoded inside the JavaScript statement (e.g. "Label1") this code will only work provided the control is defined in the Page or master page. Moving the control and the JavaScript code into a userc control with ID "UserControl1" will fail at runtime because the control will now render as:
<span id="UserControl1_Label1">Label</span>
That's why you should prefer using the "<%= Label1.ClientID%>" syntax to get the client-side id of server controls.
Additionaly the ClientID is used in ASP.NET Ajax as the unique identifier of client-side controls. Thus the following JavaScript statement is commonly used:
var control = $find("<%= MyControl1.ClientID %>");

0 comments:

Rajesh's C# blogs 4 u: Get the application root path in Win Application i...

Rajesh's C# blogs 4 u: Get the application root path in Win Application i...: "Hi friends Here is the code to find the root path of the window application through this code. before using this code you should use the S..."

0 comments:

Get the application root path in Win Application in C#.net

Hi friends

Here is the code to find the root path of the window application through this code.
before using this code you should use the System.IO namespace .

string sPath= System.IO.Directory.GetParent(System.Windows.Forms.Application.ExecutablePath).Parent.Parent.FullName + "\\pic\\" + openFileDialog1.SafeFileName.ToString(); 

Regards,
Rajesh

0 comments:

Code Snippets (C#) easy shortcuts for C# programming

Visual Studio provides a new feature called code snippets. You can use code snippets to type a short alias, and then expand it into a common programming construct. For example, the for code snippet creates an empty for loop.
Code snippets are normally used in the Code Editor by typing a short name for the alias — a code snippet shortcut — then pressing TAB. The IntelliSense menu also offers an Insert Code Snippet menu command, providing a list of available code snippets for insertion into the Code Editor. You can activate the code snippet list by typing CTRL+K, then X.
When a field is selected, users can type a new value for the field. Pressing TAB cycles through the editable fields of the code snippet; pressing SHIFT+TAB cycles through them in reverse order. Clicking on a field places the cursor in the field, and double-clicking on a field selects it. When a field is highlighted, a tooltip might be displayed, offering a description of the field.
Pressing ENTER or ESC will cancel field editing and return the Code Editor to normal.
The following procedures describe how to use code snippets. Code snippets are available in five ways: through a keyboard shortcut, through IntelliSense auto-completion, through the IntelliSense complete word list, through the Edit menu, and through the context menu.

To use code snippets through keyboard shortcut

  1. In the Visual Studio IDE, open the file that you intend to edit.
  2. In the Code Editor, place the cursor where you would like to insert the code snippet.
  3. Type CTRL+K, CTRL+X.
  4. Select the code snippet from the code snippet inserter and then press TAB or ENTER.
    Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.

To use code snippets through IntelliSense auto-completion

  1. In the Visual Studio IDE, open the file that you intend to edit.
  2. In the Code Editor, place the cursor where you would like to insert the code snippet.
  3. Type the shortcut for the code snippet that you want to add to your code.
  4. Type TAB, TAB to invoke the code snippet.

To use code snippets through the IntelliSense Complete Word list

  1. In the Visual Studio IDE, open the file that you intend to edit.
  2. In the Code Editor, place the cursor where you would like to insert the code snippet.
  3. Begin typing the shortcut for the code snippet that you want to add to your code. If automatic completion is turned on, then the IntelliSense complete word list will be displayed. If it does not appear, then press CTRL+SPACE to activate it.
  4. Select the code snippet from the complete word list.
  5. Type TAB, TAB to invoke the code snippet.

To use code snippets through the Edit menu

  1. In the Visual Studio IDE, open the file that you intend to edit.
  2. In the Code Editor, place the cursor where you would like to insert the code snippet.
  3. From the Edit menu, select IntelliSense and then select the Insert Snippet command.
  4. Select the code snippet from the code snippet inserter and then press TAB or ENTER.
    Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.

To use code snippets through the context menu

  1. In the Visual Studio IDE, open the file that you intend to edit.
  2. In the Code Editor, place the cursor where you would like to insert the code snippet.
  3. Right-click the cursor and then select the Insert Snippet command from the context menu.
  4. Select the code snippet from the code snippet inserter and then press TAB or ENTER.
    Alternatively, you can type the name of the code snippet, and then press TAB or ENTER.
For Example 

I am using this snippets in my .cs code file i simple press Control Key + K and then press X key .then you will get a screen like this .
 
then press Enter Key

then select the type that you want to use and finally you get the empty block of code.


    0 comments:

    Shut down or Run any process in computer system through C#

    Hi friend 


       Here i am going to show you how to run any process even its a shut down , execute any exe etc. for this propose we have to use System.Diagnostics Namespace. 
    The System.Diagnostics namespaces contain types that enable you to interact with system processes, event logs, and performance counters. Child namespaces contain types to interact with code analysis tools, to support contracts, to extend design-time support for application monitoring and instrumentation, to log event data using the Event Tracing for Windows (ETW) tracing subsystem, to read to and write from event logs and collect performance data, and to read and write debug symbol information.


    for example .
    The following example first spawns an instance of Internet Explorer and displays the contents of the Favorites folder in the browser. It then starts some other instances of Internet Explorer and displays some specific pages or sites. Finally it starts Internet Explorer with the window being minimized while navigating to a specific site.





    using System;
    using System.Diagnostics;
    using System.ComponentModel;
    
    namespace MyProcessSample
    {
        class MyProcess
        {
            // Opens the Internet Explorer application.
            void OpenApplication(string myFavoritesPath)
            {
                // Start Internet Explorer. Defaults to the home page.
                Process.Start("IExplore.exe");
    
                // Display the contents of the favorites folder in the browser.
                Process.Start(myFavoritesPath);
            }
    
            // Opens urls and .html documents using Internet Explorer.
            void OpenWithArguments()
            {
                // url's are not considered documents. They can only be opened
                // by passing them as arguments.
                Process.Start("IExplore.exe", "www.northwindtraders.com");
    
                // Start a Web page using a browser associated with .html and .asp files.
                Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
                Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
            }
    
            // Uses the ProcessStartInfo class to start new processes,
            // both in a minimized mode.
            void OpenWithStartInfo()
            {
                ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
                startInfo.WindowStyle = ProcessWindowStyle.Minimized;
    
                Process.Start(startInfo);
    
                startInfo.Arguments = "www.northwindtraders.com";
    
                Process.Start(startInfo);
            }
    
            static void Main()
            {
                // Get the path that stores favorite links.
                string myFavoritesPath =
                    Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
    
                MyProcess myProcess = new MyProcess();
    
                myProcess.OpenApplication(myFavoritesPath);
                myProcess.OpenWithArguments();
                myProcess.OpenWithStartInfo();
            }
        }
    }

     --------Shut down the system---------

    The easiest way to shutdown, restart, or hibernate a computer programmatically using C# is to use the shutdown command-line tool that comes with Windows. This tool has a lot of options, for example /l logs of the user, /s shuts down the computer, /r restarts the computer, and /h hibernates the computer. To get the full list of available options, type help shutdown the Command Prompt.
    To execute shutdown from C# use the follow statement:

    1. //the first parameter is the command, and the second is its arguments  
    2. system. Diagnostics.Process.Start("shutdown","/s");
    for further details check out to MSDN click here

    Regards ,

    Rajesh

    0 comments:

    Call java script function through Code behind (.cs) in C#

    Hi friends
            Here is the code to call a java script function from the .cs page of the asp.net application.
    lets take aspx page and drag a button on it.

    the source code should be like this ,

    <asp:Button ID="btnAction" runat="server" onclick="btnAction_Click" Text="Action" />


    Now come to the .cs file ,


     protected void btnAction_Click(object sender, EventArgs e)
        {
            string myscript = "alert ('Rajesh C# Blog 4 U');";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", myscript, true);
        }



    Registers the client script with the Page object using a type, key, and script literal.

    Namespace:  System.Web.UI
    Assembly:  System.Web (in System.Web.dll)

    Parameters

    type
    Type: System::Type The type of the client script to register. 
    key
    Type: System::String The key of the client script to register. 
    script
    Type: System::String The client script literal to register. 
    Hope this will helps you 
    Regards,
    Rajesh

    2 comments:

    How your Asp.Net application Speek !!!

    Hi Friends ,
                      Some time we need to convert convert Text to Speech . for this you should use System.Speech namespace provides a managed wrapper for the Speech API (SAPI). In this namespace you can find classes not only for Text-To-Speech but for Speech Recognition as well. All you have to do is add a reference to it from your project . here i am show you how to simple convert text to speech but in my next blog i will show how to get infomation from any source i.e url or text file and get the sound file .

    use this namespace    


    using System.Speech.Synthesis; 

    static void Main(string[] args)
            {
                SpeechSynthesizer synth = new SpeechSynthesizer();
                synth.Speak("Welcome to itneeds4u");
                synth.Speak(" for fruther details check out to Rajesh's Blogs only 4 you!!!");
                synth.Dispose();
               
            }


    Regards,
     Rajesh

    2 comments:

    (MCTS) Web Applications Development with Microsoft .NET Framework 4

    Hi friends
    I'm delighted to be able to announce that I'm now an  Microsoft Certified Technology Specialist (MCTS) on  Web Applications Development with Microsoft .NET Framework 4 . and i am suggesting to all the Dot Net Professional to go for it and show your technical skills to the company requiters. Here i am maintain the proper details for the MCTS Exams.
    About this Exam
    This exam is designed to test the candidate's knowledge and skills for developing Web applications using ASP.NET and the .NET Framework 4.
    Questions that contain code will be presented in either VB or C#.  Candidates can select one of these languages when they start the exam.
    Audience Profile
    Candidates for this exam are professional Web developers who use Microsoft Visual Studio. Candidates should have a minimum of two to three years of experience developing Web-based applications by using Visual Studio and Microsoft ASP.NET. Candidates should be experienced users of Visual Studio 2008 and later releases and should have a fundamental knowledge of the .NET Framework 4 programming languages (C# or Microsoft Visual Basic). In addition, candidates should understand how to use the new features of Visual Studio 2010 and the .NET Framework 4.
    Candidates should also have a minimum of one year of experience with the following:
    • Accessing data by using Microsoft ADO.NET and LINQ
    • Creating and consuming Web and Windows Communication Foundation (WCF) services
    • State management
    • ASP.NET configuration
    • Debugging and deployment
    • Application and page life-cycle management
    • Security aspects such as authentication and authorization
    • Client-side scripting languages
    • Internet Information Server (IIS)
    • ASP.NET MVC
    Credit Toward CertificationWhen you pass Exam 70-515: TS: Web Applications Development with Microsoft .NET Framework 4, you complete the requirements for the following certification(s):
    • MCTS: .NET Framework 4, Web Applications
    Exam 70-515: TS: Web Applications Development with Microsoft .NET Framework 4: counts as credit toward the following certification(s):
    • MCPD: Web Developer 4
    Note This preparation guide is subject to change at any time without prior notice and at the sole discretion of Microsoft. Microsoft exams might include adaptive testing technology and simulation items. Microsoft does not identify the format in which exams are presented. Please use this preparation guide to prepare for the exam, regardless of its format.
    ----------------------------------------Skills Being Measured------------------------------------------
    This exam measures your ability to accomplish the technical tasks listed below.The percentages indicate the relative weight of each major topic area on the exam.
    Developing Web Forms Pages (19%)
    • Configure Web Forms pages.

      This objective may include but is not limited to: page directives such as ViewState, request validation, event validation, MasterPageFile; ClientIDMode; using web.config; setting the html doctype

      This objective does not include: referencing a master page; adding a title to a Web form
    • Implement master pages and themes.

      This objective may include but is not limited to: creating and applying themes; adding multiple content placeholders; nested master pages; control skins; passing messages between master pages; switching between themes at runtime; loading themes at run time; applying a validation schema

      This objective does not include: creating a master page; basic content pages
    • Implement globalization.
      This objective may include but is not limited to: resource files, browser files, CurrentCulture, currentUICulture, ASP:Localize
    • Handle page life cycle events.
      This objective may include but is not limited to: IsPostback, IsValid, dynamically creating controls, control availability within the page life cycle, accessing control values on postback, overriding page events
    • Implement caching.
      This objective may include but is not limited to: data caching; page output caching; control output caching; cache dependencies; setting cache lifetimes; substitution control
      This objective does not include: distributed caching (Velocity)
    • Manage state.
      This objective may include but is not limited to: server-side technologies, for example, session and application; client-side technologies, for example, cookies and ViewState; configuring session state (in proc, state server, Microsoft SQL Server; cookieless); session state compression; persisting data by using ViewState; compressing ViewState; moving ViewState
    Developing and Using Web Forms Controls (18%)

    • Validate user input.

      This objective may include but is not limited to: client side, server side, and via AJAX; custom validation controls; regex validation; validation groups; datatype check; jQuery validation

      This objective does not include: RangeValidator and RequiredValidator
    • Create page layout.

      This objective may include but is not limited to: AssociatedControlID; Web parts; navigation controls; FileUpload controls

      This objective does not include:  label; placeholder, panel controls; CSS, HTML, referencing CSS files, inlining
    • Implement user controls.
      This objective may include but is not limited to: registering a control; adding a user control; referencing a user control; dynamically loading a user control; custom event; custom properties; setting toolbox visibility
    • Implement server controls.

      This objective may include but is not limited to: composite controls, INamingContainer, adding a server control to the toolbox, global assembly cache, creating a custom control event, globally registering from web.config; TypeConverters

      This objective does not include: postback data handler, custom databound controls, templated control
    • Manipulate user interface controls from code-behind.

      This objective may include but is not limited to: HTML encoding to avoid cross-site scripting, navigating through and manipulating the control hierarchy; FindControl; controlRenderingCompatibilityVersion; URL encoding; RenderOuterTable

      This objective does not include: Visibility, Text, Enabled properties
    Implementing Client-Side Scripting and AJAX (16%)

    • Add dynamic features to a page by using JavaScript.
      This objective may include but is not limited to: referencing c
      lient ID; Script Manager; Script combining; Page.clientscript.registerclientscriptblock; Page.clientscript.registerclientscriptinclude; sys.require (scriptloader)
      This objective does not include: interacting with the server; referencing JavaScript files; inlining JavaScript
    • Alter a page dynamically by manipulating the DOM.

      This objective may include but is not limited to: using jQuery, adding, modifying, or removing page elements, adding effects, jQuery selectors

      This objective does not include: AJAX
    • Handle JavaScript events.
      This objective may include but is not limited to: DOM events, custom events, handling events by using jQuery
    • Implement ASP.NET AJAX.

      This objective may include but is not limited to: client-side templating, creating a script service, extenders (ASP.NET AJAX Control Toolkit), interacting with the server, Microsoft AJAX Client Library, custom extenders; multiple update panels; triggers; UpdatePanel.UpdateMode; Timer

      This objective does not include: basic update panel and progress
    • Implement AJAX by using jQuery.

      This objective may include but is not limited to: $.get, $.post, $.getJSON, $.ajax, xml, html, JavaScript Object Notation (JSON), handling return types

      This objective does not include: creating a service
    Configuring and Extending a Web Application (15%)

    • Configure authentication and authorization.

      This objective may include but is not limited to: using membership, using login controls, roles, location element, protecting an area of a site or a page

      This objective does not include:  Windows Live; Microsoft Passport; Windows and Forms authentication
    • Configure providers.

      This objective may include but is not limited to: role, membership, personalization, aspnet_regsql.exe

      This objective does not include: creating custom providers
    • Create and configure HttpHandlers and HttpModules.
      This objective may include but is not limited to: generic handlers, asynchronous handlers, setting MIME types and other content headers, wiring modules to application events
    • Configure initialization and error handling.
      This objective may include but is not limited to: handling Application_Start, Session_Start, and Application_BeginRequest in global.asax, capturing unhandled exceptions, custom error section of web.config, redirecting to an error page; try and catch; creating custom exceptions
    • Reference and configure ASMX and WCF services.

      This objective may include but is not limited to: adding service reference, adding Web reference, changing endpoints, wsdl.exe, svcutil.exe; updating service URL; shared WCF contracts assembly

      This objective does not include: creating WCF and ASMX services
    • Configure projects and solutions, and reference assemblies.
      This objective may include but is not limited to: local assemblies, shared assemblies (global assembly cache), Web application projects, solutions, settings file, configuring a Web application by using web.config or multiple .config files; assemblyinfo
    • Debug a Web application.
      This objective may include but is not limited to: remote, local, JavaScript debugging, attaching to process, logging and tracing, using local IIS, aspnet_regiis.exe
    • Deploy a Web application.

      This objective may include but is not limited to: pre-compilation, publishing methods (e.g.,
       MSDeploy, xcopy, and FTP), deploying an MVC application

      This objective does not include: application pools, IIS configuration
    Displaying and Manipulating Data (19%)

    • Implement data-bound controls.

      This objective may include but is not limited to: advanced customization of DataList, Repeater, ListView, FormsView, DetailsView, TreeView, DataPager, Chart, GridView

      This objective does not include: working in Design mode
    • Implement DataSource controls.

      This objective may include but is not limited to: ObjectDataSource, LinqDataSource, XmlDataSource, SqlDataSource, QueryExtender, EntityDataSource

      This objective does not include: AccessDataSource, SiteMapDataSource
    • Query and manipulate data by using LINQ.

      This objective may include but is not limited to: transforming data by using LINQ to create XML or JSON, LINQ to SQL, LINQ to Entities, LINQ to objects, managing DataContext lifetime

      This objective does not include: basic LINQ to SQL
    • Create and consume a data service.

      This objective may include but is not limited to: WCF, Web service; server to server calls; JSON serialization, XML serialization

      This objective does not include: client side, ADO.NET Data Services
    • Create and configure a Dynamic Data project.
      This objective may include but is not limited to: dynamic data controls, custom field templates; connecting to DataContext and ObjectContext
    Developing a Web Application by Using ASP.NET MVC 2 (13%)

    • Create custom routes.
      This objective may include but is not limited to: route constraints, route defaults, ignore routes, custom route parameters
    • Create controllers and actions.
      This objective may include but is not limited to: Visual Studio support for right-click context menus; action filters (including Authorize, AcceptVerbs, and custom) and model binders; ActionResult sub-classes
    • Structure an ASP.NET MVC application.
      This objective may include but is not limited to: single project areas (for example, route registration, Visual Studio tooling, and inter-area links); organizing controllers into areas; shared views; content files and folders
    • Create and customize views.

      This objective may include but is not limited to: built-in and custom HTML helpers (for example, HTML.RenderAction and HTML.RenderPartial), strongly typed views, static page checking, templated input helpers, ViewMasterPage, ViewUserControl

      This objective does not include: Microsoft.Web.Mvc Futures assembly
    All the other details available on Microsoft offical Site click here
    Regards,

    Rajesh

    1 comments:

    C# Read Text File Line-by-Line


    Hi friends,
    this is a C# code for read the .txt file line by line . which is some the we need to use in our Programming. Hope it will help you...

    using System;
    using System.IO;

    namespace TestReadLine
    {
        class Program
        {
            static void Main(string[] args)
            {
                string filePath = @"c:\YourFile.txt";
                string line;
                int count = 0;
                if (File.Exists(filePath))
                {
                    StreamReader file = null;
                    try
                    {
                        file = new StreamReader(filePath);
                        while ((line = file.ReadLine()) != null)
                        {
                            Console.WriteLine(line);
                            count = count + 1;
                        }
                    }
                    finally
                    {
                        Console.WriteLine("Total No of line is Used :"+count);
                        if (file != null)
                            file.Close();
                    }
                }

                Console.ReadLine();
            }
        }
    }


    -----------------------------------------------------------------------------
    This is a Method Use to replace the string in the .txt file

    using System.Text.RegularExpressions;

    static public void ReplaceInFile(string filePath, string searchText, string replaceText)
            {
                StreamReader reader = new StreamReader(filePath);
                string content = reader.ReadToEnd();
                reader.Close();

                content = Regex.Replace(content, searchText, replaceText);

                StreamWriter writer = new StreamWriter(filePath);
                writer.Write(content);
                writer.Close();
            }
    Regards ,
    Rajesh

    0 comments: