How to Split Text Files into Lines in C# .NET Framework

Cloudmersive
2 min readFeb 16, 2024

Each line in a text file is cleanly separated from the next, and this makes programmatically extracting individual lines from text files extremely easy.

Using the ready-to-run code provided below, we can take advantage of a free & easy-to-use API solution to programmatically divide a text file into separate lines. Each line will be returned in its own individual response object labeled by the original line number, and towards the bottom of our API response we’ll get a full line count from our original text file.

To make our API call for free, we’ll just need a free-tier Cloudmersive API key. This will allow a limit of 800 API calls per month with no commitments.

We can then structure our API call in two quick steps.

First, let’s install the SDK. We can run the following command in our Package Manager console to install via NuGet:

Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.4.2

Next, let’s input our API key and file bytes into the function:

using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;
using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;

namespace Example
{
public class SplitDocumentTxtByLineExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");

var apiInstance = new SplitDocumentApi();
var inputFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Input file to perform the operation on.

try
{
// Split a single Text file (txt) into lines
SplitTextDocumentByLinesResult result = apiInstance.SplitDocumentTxtByLine(inputFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling SplitDocumentApi.SplitDocumentTxtByLine: " + e.Message );
}
}
}
}

Just like that, we can easily split up text files line-by-line with minimal code.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.