unit CSVHelper;
interface
uses
Classes, SysUtils;
type
TStringListCSVHelper =
class helper
for TStringList
public
procedure LoadFromCSVStream(Stream: TStream);
overload;
virtual;
procedure LoadFromCSVStream(Stream: TStream; Encoding: TEncoding);
overload;
virtual;
procedure LoadFromCSVFile(
const FileName:
string);
overload;
virtual;
procedure LoadFromCSVFile(
const FileName:
string; Encoding: TEncoding);
overload;
virtual;
procedure SaveToCSVStream(Stream: TStream);
overload;
virtual;
procedure SaveToCSVStream(Stream: TStream; Encoding: TEncoding);
overload;
virtual;
procedure SaveToCSVFile(
const FileName:
string);
overload;
virtual;
procedure SaveToCSVFile(
const FileName:
string; Encoding: TEncoding);
overload;
virtual;
end;
implementation
{TStringListCSVHelper]}
procedure TStringListCSVHelper.LoadFromCSVStream(Stream: TStream);
var
Buffer: TBytes;
Encoding: TEncoding;
begin
Stream.ReadData(Buffer);
TEncoding.GetBufferEncoding(Buffer, Encoding);
DelimitedText := Encoding.GetString(Buffer);
end;
procedure TStringListCSVHelper.LoadFromCSVStream(Stream: TStream; Encoding: TEncoding);
var
Buffer: TBytes;
begin
Stream.ReadData(Buffer);
DelimitedText := Encoding.GetString(Buffer);
end;
procedure TStringListCSVHelper.LoadFromCSVFile(
const FileName:
string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName);
try
LoadFromCSVStream(Stream);
finally
Stream.Free;
end;
end;
procedure TStringListCSVHelper.LoadFromCSVFile(
const FileName:
string; Encoding: TEncoding);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead);
try
LoadFromCSVStream(Stream, Encoding);
finally
Stream.Free;
end;
end;
procedure TStringListCSVHelper.SaveToCSVStream(Stream: TStream);
begin
SaveToCSVStream(Stream, Encoding);
end;
procedure TStringListCSVHelper.SaveToCSVStream(Stream: TStream; Encoding: TEncoding);
var
Buffer: TBytes;
begin
Buffer := Encoding.GetBytes(DelimitedText);
Stream.WriteData(Buffer);
end;
procedure TStringListCSVHelper.SaveToCSVFile(
const FileName:
string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenWrite);
try
SaveToCSVStream(Stream);
finally
Stream.Free;
end;
end;
procedure TStringListCSVHelper.SaveToCSVFile(
const FileName:
string; Encoding: TEncoding);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenWrite);
try
SaveToCSVStream(Stream, Encoding);
finally
Stream.Free;
end;
end;
end.