コメント
コメントの投稿
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。
using Jcifs;
using Jcifs.Smb;
using Xamarin.Forms;
using System.Threading.Tasks;
using System.Collections.Generic;
[assembly: Dependency(typeof(SmbService))]
public class SmbService : ISmbService
{
private UniAddress _domain = null;
private NtlmPasswordAuthentication _auth = null;
private HostInfo _hostInfo = null;
private SmbFile _smbFile = null;
private bool _isLogon = false;
/// <summary>
/// SmbFileインスタンスを保持する
/// </summary>
/// <param name="path">フルパス</param>
private void CreateSmbInstance(string path)
{
if (_smbFile != null && _smbFile.Path.Equals(path))
{
//pathが変更ない場合はインスタンスを使いまわす。
return;
}
else if (_smbFile != null)
{
_smbFile.Dispose();
}
_smbFile = new SmbFile(path, this._auth);
}
/// <summary>
/// ホスト情報の受け渡し
/// </summary>
/// <param name="hostInfo">ホスト情報</param>
public void SetHostInfo(HostInfo hostInfo)
{
if (hostInfo == null)
{
throw new Exception("Hostinfo is not set.");
}
_hostInfo = hostInfo;
}
/// <summary>
/// ログオン処理
/// </summary>
public void Logon(ref string err)
{
if (_hostInfo == null)
{
throw new Exception("Hostinfo is not set.");
}
//ログイン処理を非同期で行う
var task = new Task<string>(() =>
{
try
{
this._domain = UniAddress.GetByName(_hostInfo.IP);
this._auth = new NtlmPasswordAuthentication(_hostInfo.IP, _hostInfo.UserName, _hostInfo.Password);
SmbSession.Logon(this._domain, this._auth);
_isLogon = true;
return String.Empty;
}
catch (Exception ex)
{
_isLogon = false;
return ex.Message;
}
});
task.Start();
task.Wait();
err = task.Result;
}
/// <summary>
/// ディレクトリ一覧を取得する
/// </summary>
/// <param name="path">検索するフルパス</param>
/// <returns>ディレクトリ一覧</returns>
public string[] GetDirectories(string path)
{
if (!_isLogon)
{
throw new Exception("You are not logged on to the remote host.");
}
var task = new Task<string[]>(() =>
{
this.CreateSmbInstance(path);
List<string> list = new List<string>();
if (_smbFile.IsDirectory)
{
foreach (SmbFile dir in _smbFile.ListFiles())
{
if (dir.IsDirectory)
{
list.Add(_smbFile.Path + dir.Name.Replace("/", ""));
}
}
return list.ToArray();
}
return null;
});
task.Start();
task.Wait();
return task.Result;
}
/// <summary>
/// ファイル一覧を取得する
/// </summary>
/// <param name="path">検索するフルパス</param>
/// <returns>ファイル一覧</returns>
public string[] GetFiles(string path)
{
if (!_isLogon)
{
throw new Exception("You are not logged on to the remote host.");
}
var task = new Task<string[]>(() =>
{
this.CreateSmbInstance(path);
List<string> list = new List<string>();
if (_smbFile.IsDirectory)
{
foreach (SmbFile dir in _smbFile.ListFiles())
{
if (dir.IsFile)
{
list.Add(_smbFile.Path + dir.Name);
}
}
return list.ToArray();
}
return null;
});
task.Start();
task.Wait();
return task.Result;
}
}
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。