You must Sign In to post a response.
  • Category: ASP.NET

    How to split string in C#

    I am displaying all the project name in dropdownlist as follows

    string sourceDirectory = Server.MapPath("~/");
    DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirectory);
    var aspxFiles = new List(Directory.GetFiles(sourceDirectory, "*.aspx", SearchOption.AllDirectories));

    foreach (string currentFile in aspxFiles)
    {
    this.ddllink.Items.Add(currentFile);
    }

    When i run in dropdownlist output as follows

    E:Projects\Reception\Default.aspx


    But i want in dropdownlist as follows Default.aspx

    i want to split after \.

    for that how can i do in asp.net using c#.

    In dropdownlist i want output as follows
    Default.aspx
  • #763351
    you can use the normal split function to do this

    Following is the tips to do this

    string[] aArrayL = "E:Projects\\Reception\\Default.aspx.Split('/')".Split('/');
    string PageNameL = aArrayL[aArrayL.Length-1];

    By Nathan
    Direction is important than speed

  • #763355
    Hi,

    As nathan suggested the simple and straight forward way to achieve this is using Split function.

    string ipstring=your path;
    string[] result=ipstring.Split('/');
    if(result.Length>0)
    string finalresult=result[result.Length-1].ToString();


    Try something like above and let us know if you face any difficulties..

    --------------------------------------------------------------------------------
    Give respect to your work, Instead of trying to impress your boss.

    N@veen
    Blog : http://naveens-dotnet.blogspot.in/

  • #763421

    string[] str = "E:Projects\Reception\Default.aspx";
    str = str.Split('/');

    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM

  • #763442
    Hi Rao.

    Try below code to get only name of the file.

    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
    </asp:CheckBoxList>
    </div>
    </form>
    protected void Page_Load(object sender, EventArgs e)
    {
    DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\sri\Desktop");
    FileInfo[] Files = dinfo.GetFiles("*.*");
    //string[] files = Directory.GetFiles(@"C:\Users\sri\Desktop");
    foreach (FileInfo currentFile in Files)
    {
    CheckBoxList1.Items.Add(currentFile.Name);
    }
    }

    Sridhar Thota.
    Editor: DNS Forum.

  • #764100
    Hi,

    Without doing lots of modifications to your code just replace line 'this.ddllink.Items.Add(currentFile);' with any of the following:
    1) this.ddllink.Items.Add(currentFile.Substring(currentFile.LastIndexOf('\\') + 1));
    2) this.ddllink.Items.Add(currentFile.Remove(0, currentFile.LastIndexOf('\\') + 1));

    Hope this will help you.

    Regards,
    Shashikant Gurav[Programmer II]
    shashikantgurav22@gmail.com


Sign In to post your comments