Read lines from file

**Correct Way Using the Sandbox **

To read a file in your function, instead of this:

using (StreamReader reader = new StreamReader(Path.Combine(filePath, FileName)))
var filePath = new FilePath(ServerFolder.CompanyData, "SubFolder", "FileName.txt");
using (var streamReader = this.Sandbox.IO.File.OpenText(filePath))
{
    string line = streamReader.ReadLine();
    this.output = $"First line: {line}";
}

Key Fixes

  • FilePath is used instead of raw string paths.
  • this.Sandbox.IO.File.OpenText(filePath) is used instead of new StreamReader(...).

Example Folder Setup

You can only use ServerFolder.CompanyData or ServerFolder.UserData. So if your file is in \\EpicorServer\CompanyData\Folder_Name\myfile.txt, the correct path would be:

var filePath = new FilePath(ServerFolder.CompanyData, "Folder_Name", "myfile.txt");

SaaS

var folderPath = new FilePath(ServerFolder.CompanyData, "Folder_Name");
folderPath.Combine(this.FileName); 
var filePath = folderPath;

I personally add sections like this to functions that use uploaded files.

// Rename the file to a unique name if it already exists
string uniqueFileName = Guid.NewGuid().ToString() + "_" + this.callContextClient.CurrentUserId + "_" + this.FileName;
var backupPath = new FilePath(ServerFolder.CompanyData, "Folder_Name");
backupPath.Combine(uniqueFileName);

if (this.Sandbox.IO.File.Exists(filePath))
{
  this.Sandbox.IO.File.Move(filePath, backupPath, overwrite: true);
  filePath = backupPath;
}