From 73e4f290ad0bf0d540602f2265b4a0ac78831e53 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Fri, 4 Oct 2019 21:39:41 -0700 Subject: [PATCH] Add ability to set directory to store sessions Now user can set directory to store sessions somewhere else other than the folder where the program's executable is. (Based on patch from Felony contributed in https://github.com/sochix/TLSharp/pull/874 ) --- TLSharp.Core/Session.cs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/TLSharp.Core/Session.cs b/TLSharp.Core/Session.cs index 6264770..8ec8adc 100644 --- a/TLSharp.Core/Session.cs +++ b/TLSharp.Core/Session.cs @@ -14,9 +14,24 @@ namespace TLSharp.Core public class FileSessionStore : ISessionStore { + private readonly DirectoryInfo basePath; + + public FileSessionStore(DirectoryInfo basePath = null) + { + if (basePath != null && !basePath.Exists) + { + throw new ArgumentException("basePath doesn't exist", nameof(basePath)); + } + this.basePath = basePath; + } + public void Save(Session session) { - using (var stream = new FileStream($"{session.SessionUserId}.dat", FileMode.OpenOrCreate)) + string sessionFileName = $"{session.SessionUserId}.dat"; + var sessionPath = basePath == null ? sessionFileName : + Path.Combine(basePath.FullName, sessionFileName); + + using (var stream = new FileStream(sessionPath, FileMode.OpenOrCreate)) { var result = session.ToBytes(); stream.Write(result, 0, result.Length); @@ -25,11 +40,14 @@ namespace TLSharp.Core public Session Load(string sessionUserId) { - var sessionFileName = $"{sessionUserId}.dat"; - if (!File.Exists(sessionFileName)) + string sessionFileName = $"{sessionUserId}.dat"; + var sessionPath = basePath == null ? sessionFileName : + Path.Combine(basePath.FullName, sessionFileName); + + if (!File.Exists(sessionPath)) return null; - using (var stream = new FileStream(sessionFileName, FileMode.Open)) + using (var stream = new FileStream(sessionPath, FileMode.Open)) { var buffer = new byte[2048]; stream.Read(buffer, 0, 2048);