Read lines from file

I am doing this in my Epicor Kinetic function…

using (StreamReader reader = new StreamReader(Path.Combine(filePath, FileName)))

and get this when I try to save, Is there something else I should be using so it will last?

The ‘System.IO.StreamReader.StreamReader(string)’ constructor cannot be called.

It is a warning now but will become an error in the future. Have you guys seen this? If so, how did you address it?

1 Like

Where is your file, I could whip up a quick example, or point you to one.

**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;
}
5 Likes

Thanks folks!!!

FTFY

Brussels Griffon What GIF

3 Likes

Go Crazy Wtf GIF