Skip to content

Instantly share code, notes, and snippets.

@rebelweb
Created November 17, 2019 03:34
Show Gist options
  • Save rebelweb/63d3fab37a2667eb5593c1b5894292d5 to your computer and use it in GitHub Desktop.
Save rebelweb/63d3fab37a2667eb5593c1b5894292d5 to your computer and use it in GitHub Desktop.
SMB File Share Access Service in C#
using System;
using System.Linq;
using System.Text;
using SMBLibrary;
namespace FileShare.Access
{
public interface IClientDTO
{
string IPAddress { get; set; }
string DomainName { get; set; }
string Username { get; set; }
string Password { get; set; }
string ShareName { get; set; }
}
public class ReadFileDTO : IClientDTO
{
public string IPAddress { get; set; }
public string DomainName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string ShareName { get; set; }
public string FileName { get; set; }
}
public class FileShareService
{
public string ReadFile(ReadFileDTO dto)
{
using (var client = new FileShareClient(dto))
{
object handle;
FileStatus status;
bool connected = client.Connect();
if (!connected)
{
Console.WriteLine("Not Connected Exiting...");
return null;
}
var share = client.Share;
NTStatus ntStatus = share.CreateFile(out handle, out status, dto.FileName,
AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN_IF,
CreateOptions.FILE_NON_DIRECTORY_FILE, null);
if (ntStatus == NTStatus.STATUS_SUCCESS)
{
byte[] data = null;
bool read = true;
int start = 0;
while (read)
{
Console.WriteLine("Reading...");
share.ReadFile(out var chuckedData, handle, start, 65536);
data = data == null ? chuckedData : data.Union(chuckedData).ToArray();
start += 65536;
if (chuckedData.Length < 65536) read = false;
}
return Encoding.UTF8.GetString(data);
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment