Split text (.txt) file into multiple files in ASP.Net using C# and VB.Net

nirmal90
 
on Feb 13, 2022 09:40 PM
2687 Views

I want to Split text file into multiple files based on header row.

Sample data (so each FILE| becomes its own datafile(n).txt file with the rows below in that file).

FILE|datafile1|25/04/17
25044|0001|37339|10380|TT75
25045|0001|37339|10398|TT75
25046|0001|78711|15940|TT75
FILE|datafile2|25/04/17
25047|0001|98745|11263|TT75
25048|0001|96960|13011|TT84
FILE|datafile3|25/04/17
25074|0001|57585|13639|TT84
25075|0001|59036|10495|TT84
FILE|datafile4|25/04/17
25076|0001|75844|13956|TT84
25077|0001|17430|01111|TT84

 

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arjunv
 
on Feb 13, 2022 11:59 PM
on Feb 14, 2022 04:11 AM

Hi nirmal90,

Please refer below sample.

HTML

<asp:Button Text="Split File" ID="btnSplit" OnClick="SpitDataFiles" runat="server" />

Namespace

C#

using System.IO;

VB.Net

Imports System.IO

Code

C#

protected void SpitDataFiles(object sender, EventArgs e)
{
    string[] lines = File.ReadAllLines(Server.MapPath("~/Files/DataFiles.txt"));
    string fileData = string.Empty;
    for (int i = 0; i < lines.Length; i++)
    {
        string fileName = Server.MapPath("~/Files/DataFiles" + (i + 1) + ".txt");
        string line = lines[i];
        if (i == 0)
        {
            fileData += line + "\n";
        }
        else if (line.StartsWith("FILE") && i != 0)
        {
            File.WriteAllText(fileName, fileData);
            fileData = string.Empty;
            fileData += line + "\n";
        }
        else
        {
            fileData += line + "\n";
        }
        if (lines.Length == i + 1)
        {
            File.WriteAllText(fileName, fileData);
        }
    }
}        

VB.Net

Protected Sub SpitDataFiles(ByVal sender As Object, ByVal e As EventArgs)
    Dim lines As String() = File.ReadAllLines(Server.MapPath("~/Files/DataFiles.txt"))
    Dim fileData As String = String.Empty

    For i As Integer = 0 To lines.Length - 1
        Dim fileName As String = Server.MapPath("~/Files/DataFiles" & (i + 1) & ".txt")
        Dim line As String = lines(i)

        If i = 0 Then
            fileData += line & vbLf
        ElseIf line.StartsWith("FILE") AndAlso i <> 0 Then
            File.WriteAllText(fileName, fileData)
            fileData = String.Empty
            fileData += line & vbLf
        Else
            fileData += line & vbLf
        End If

        If lines.Length = i + 1 Then
            File.WriteAllText(fileName, fileData)
        End If
    Next
End Sub

Screenshot