public static async Task <SMBFileShare> ConnectAsync(IPAddress address, string share, string username = "", string password = "") { return(await Task.Run(() => { SMB2Client client = new SMB2Client(); bool isConnected = client.Connect(address, SMBTransportType.DirectTCPTransport); if (!isConnected) { throw new Exception($"Could not connect to {address}"); } NTStatus status = client.Login(string.Empty, username, password); if (status != NTStatus.STATUS_SUCCESS) { throw new Exception($"Could not login: {status}"); } ISMBFileStore fileStore = client.TreeConnect(share, out status); if (status != NTStatus.STATUS_SUCCESS) { throw new Exception($"Could not access share: {status}"); } return new SMBFileShare(client, fileStore); }).ConfigureAwait(false)); }
protected SmbClient(string path) { _connectionKey = MakeKey(path); Client = new SMB2Client(); var uri = new Uri(path); IPAddress.TryParse(uri.Host, out var ip); if (ip?.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { ip = null; } int retry = 0; while (ip == null && retry < 5) { var host = Dns.GetHostEntry(uri.Host); ip = host.AddressList.FirstOrDefault(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); retry++; } Sharename = SharenameFromUri(uri); if (!Client.Connect(ip, SMBTransportType.DirectTCPTransport)) { throw new IOException("Cannot connect to SMB host."); } ThrowOnError(Client.Login("", "", "")); if (!string.IsNullOrEmpty(Sharename)) { FileStore = Client.TreeConnect(Sharename, out var status); ThrowOnError(status); } }
public ISMBClient CreateClient(uint maxBufferSize) { var client = new SMB2Client { ClientMaxReadSize = maxBufferSize, ClientMaxWriteSize = maxBufferSize, ClientMaxTransactSize = maxBufferSize }; return(client); }
public IActionResult Get(string fileName) { var client = new SMB2Client(); client.Connect(IPAddress.Parse("192.168.1.166"), SMBTransportType.DirectTCPTransport); client.Login("WORKGROUP", "Alon Amrani", "alon1023"); var tree = client.TreeConnect("Users", out var e); var result = tree.CreateFile(out var h, out var status, $"Efrat\\Desktop\\Hackathon\\AlonShare\\{fileName}", AccessMask.GENERIC_ALL, FileAttributes.Normal, ShareAccess.Read, CreateDisposition.FILE_CREATE, CreateOptions.FILE_NON_DIRECTORY_FILE, null); return(Ok()); }
public PipeClient(string serverName, string pipeName, PipeDirection direction, string strUserName, string strPassword) { SMB2Client = new SMB2Client(serverName, strUserName, strPassword); PipeName = pipeName; if (direction == PipeDirection.Read) { FilePipePrinterAccessMaskFlags = FilePipePrinterAccessMaskFlags.GENERIC_READ; } else if (direction == PipeDirection.Write) { FilePipePrinterAccessMaskFlags = FilePipePrinterAccessMaskFlags.GENERIC_WRITE; } else { FilePipePrinterAccessMaskFlags = FilePipePrinterAccessMaskFlags.GENERIC_READ | FilePipePrinterAccessMaskFlags.GENERIC_WRITE; } }
public async Task <IActionResult> td([FromBody] DocumentModel[] docs) { if (docs.Length == 0) { return(new NoContentResult()); } SMB2Client client = new SMB2Client(); string site = docs[0].site; string url = _baseurl + "sites/" + site; string listname = docs[0].list; Guid listGuid = new Guid(listname); using (ClientContext cc = AuthHelper.GetClientContextForUsernameAndPassword(url, _username, _password)) try { SMBCredential SMBCredential = new SMBCredential() { username = Environment.GetEnvironmentVariable("smb_username"), password = Environment.GetEnvironmentVariable("smb_password"), domain = Environment.GetEnvironmentVariable("domain"), ipaddr = Environment.GetEnvironmentVariable("ipaddr"), share = Environment.GetEnvironmentVariable("share"), }; var serverAddress = System.Net.IPAddress.Parse(SMBCredential.ipaddr); bool success = client.Connect(serverAddress, SMBTransportType.DirectTCPTransport); NTStatus nts = client.Login(SMBCredential.domain, SMBCredential.username, SMBCredential.password); ISMBFileStore fileStore = client.TreeConnect(SMBCredential.share, out nts); List list = cc.Web.Lists.GetById(listGuid); List <Metadata> fields = SharePointHelper.GetFields(cc, list); //List list = cc.Web.Lists.GetByTitle(listname); for (int i = 0; i < docs.Length; i++) { string filename = docs[i].filename; string file_url = docs[i].file_url; var inputFields = docs[i].fields; var taxFields = docs[i].taxFields; FileCreationInformation newFile = SharePointHelper.GetFileCreationInformation(file_url, filename, SMBCredential, client, nts, fileStore); ///FileCreationInformation newFile = SharePointHelper.GetFileCreationInformation(file_url, filename); if (newFile == null) { _logger.LogError("Failed to upload. Skip: " + filename); continue; } File uploadFile; if (docs[i].foldername == null) { uploadFile = list.RootFolder.Files.Add(newFile); } else { string foldername = docs[i].foldername; string sitecontent = docs[i].sitecontent; //Folder folder = list.RootFolder.Folders.GetByUrl(foldername); Folder folder = SharePointHelper.GetFolder(cc, list, foldername); if (folder == null && taxFields != null) { folder = SharePointHelper.CreateDocumentSetWithTaxonomy(cc, list, sitecontent, foldername, inputFields, fields, taxFields); } else if (folder == null) { folder = SharePointHelper.CreateFolder(cc, list, sitecontent, foldername, inputFields, fields); } //cc.ExecuteQuery(); uploadFile = folder.Files.Add(newFile); } _logger.LogInformation("Upload file: " + newFile.Url); ListItem item = uploadFile.ListItemAllFields; if (taxFields != null) { var clientRuntimeContext = item.Context; for (int t = 0; t < taxFields.Count; t++) { var inputField = taxFields.ElementAt(t); var fieldValue = inputField.Value; var field = list.Fields.GetByInternalNameOrTitle(inputField.Key); cc.Load(field); cc.ExecuteQuery(); var taxKeywordField = clientRuntimeContext.CastTo <TaxonomyField>(field); Guid _id = taxKeywordField.TermSetId; string _termID = TermHelper.GetTermIdByName(cc, fieldValue, _id); TaxonomyFieldValue termValue = new TaxonomyFieldValue() { Label = fieldValue.ToString(), TermGuid = _termID, }; taxKeywordField.SetFieldValueByValue(item, termValue); taxKeywordField.Update(); } } DateTime dtMin = new DateTime(1900, 1, 1); Regex regex = new Regex(@"~t.*"); if (inputFields != null) { foreach (KeyValuePair <string, string> inputField in inputFields) { if (inputField.Value == null || inputField.Value == "") { continue; } string fieldValue = inputField.Value; Match match = regex.Match(fieldValue); Metadata field = fields.Find(x => x.InternalName.Equals(inputField.Key)); if (field.TypeAsString.Equals("User")) { int uid = SharePointHelper.GetUserId(cc, fieldValue); item[inputField.Key] = new FieldUserValue { LookupId = uid }; } //endre hard koding else if (inputField.Key.Equals("Modified_x0020_By") || inputField.Key.Equals("Created_x0020_By") || inputField.Key.Equals("Dokumentansvarlig")) { StringBuilder sb = new StringBuilder("i:0#.f|membership|"); sb.Append(fieldValue); item[inputField.Key] = sb; } else if (match.Success) { fieldValue = fieldValue.Replace("~t", ""); if (DateTime.TryParse(fieldValue, out DateTime dt)) { if (dtMin <= dt) { item[inputField.Key] = dt; _logger.LogInformation("Set field " + inputField.Key + "to " + dt); } else { continue; } } } else { item[inputField.Key] = fieldValue; _logger.LogInformation("Set " + inputField.Key + " to " + fieldValue); } } item.Update(); } try { await cc.ExecuteQueryAsync(); Console.WriteLine("Successfully uploaded " + newFile.Url + " and updated metadata"); } catch (System.Exception e) { _logger.LogError("Failed to update metadata."); Console.WriteLine(e); continue; } } } catch (System.Exception) { throw; } finally { client.Logoff(); client.Disconnect(); } return(new NoContentResult()); }
/// <summary> /// /// </summary> /// <param name="docs"></param> /// <returns></returns> public async Task <IActionResult> Test([FromBody] DocumentModel[] docs) { if (docs.Length == 0) { return(new NoContentResult()); } SMB2Client client = new SMB2Client(); string site = docs[0].site; string url = _baseurl + "sites/" + site; string listname = docs[0].list; Guid listGuid = new Guid(listname); using (ClientContext cc = AuthHelper.GetClientContextForUsernameAndPassword(url, _username, _password)) try { ///SMBCredential SMBCredential = new SMBCredential(){ /// username = Environment.GetEnvironmentVariable("smb_username"), /// password = Environment.GetEnvironmentVariable("smb_password"), /// domain = Environment.GetEnvironmentVariable("domain"), /// ipaddr = Environment.GetEnvironmentVariable("ipaddr"), /// share = Environment.GetEnvironmentVariable("share"), ///}; /// ///var serverAddress = System.Net.IPAddress.Parse(SMBCredential.ipaddr); ///bool success = client.Connect(serverAddress, SMBTransportType.DirectTCPTransport); /// ///NTStatus nts = client.Login(SMBCredential.domain, SMBCredential.username, SMBCredential.password); ///ISMBFileStore fileStore = client.TreeConnect(SMBCredential.share, out nts); List list = cc.Web.Lists.GetById(listGuid); var fieldcollection = list.Fields; cc.Load(fieldcollection); cc.ExecuteQuery(); var cquery = new CamlQuery(); cquery.ViewXml = string.Format(@"<View> <Query> <Where> <Eq><FieldRef Name='Title' /> <Value Type='Text'>{0}</Value></Eq> </Where> </Query> </View>", "dummy.pdf"); var listitems = list.GetItems(cquery); cc.Load(listitems); cc.ExecuteQuery(); ListItem item = listitems[0]; var clientRuntimeContext = item.Context; string[] SPORDocPropertyNo = { "4223-7/1", "4223-7/3", "4223-7/4", "4223-7/5" }; foreach (var fieldObj in fieldcollection) { if (fieldObj.InternalName.Equals("SPORDocPropertyNo")) { var taxKeywordField = clientRuntimeContext.CastTo <TaxonomyField>(fieldObj); Guid _id = taxKeywordField.TermSetId; List <string> ListTermString = new List <string>(); for (int i = 0; i < SPORDocPropertyNo.Length; i++) { string _termID = TermHelper.GetTermIdByName(cc, SPORDocPropertyNo[i], _id); ListTermString.Add(string.Format("-1;#{0}{1}{2}", SPORDocPropertyNo[i], "|", _termID)); } string tax = string.Join(";#", ListTermString); Console.WriteLine(tax); taxKeywordField.SetFieldValueByValueCollection(item, new TaxonomyFieldValueCollection(cc, tax, taxKeywordField)); taxKeywordField.Update(); break; } } item.Update(); await cc.ExecuteQueryAsync(); } catch (System.Exception) { throw; } finally { //client.Logoff(); //client.Disconnect(); } return(new NoContentResult()); }
public static Microsoft.SharePoint.Client.File GetBigSharePointFile(string fileurl, string filename, SMBCredential SMBCredential, SMB2Client client, NTStatus nts, ISMBFileStore fileStore, List list, ClientContext cc, DocumentModel doc, List <Metadata> fields) { Microsoft.SharePoint.Client.File uploadFile = null; ClientResult <long> bytesUploaded = null; //SMBLibrary.NTStatus actionStatus; FileCreationInformation newFile = new FileCreationInformation(); NTStatus status = nts; object handle; FileStatus fileStatus; string tmpfile = Path.GetTempFileName(); status = fileStore.CreateFile(out handle, out fileStatus, fileurl, AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE, null); if (status != NTStatus.STATUS_SUCCESS) { Console.WriteLine(status); return(null); } else { string uniqueFileName = String.Empty; int blockSize = 8000000; // 8 MB long fileSize; Guid uploadId = Guid.NewGuid(); byte[] buf; var fs = new FileStream(tmpfile, FileMode.OpenOrCreate); var bw = new BinaryWriter(fs); int bufsz = 64 * 1000; int i = 0; do { status = fileStore.ReadFile(out buf, handle, i * bufsz, bufsz); if (status == NTStatus.STATUS_SUCCESS) { int n = buf.GetLength(0); bw.Write(buf, 0, n); if (n < bufsz) { break; } i++; } }while (status != NTStatus.STATUS_END_OF_FILE && i < 1000); if (status == NTStatus.STATUS_SUCCESS) { fileStore.CloseFile(handle); bw.Flush(); fs.Close(); //fs = System.IO.File.OpenRead(tmpfile); //byte[] fileBytes = new byte[fs.Length]; //fs.Read(fileBytes, 0, fileBytes.Length); try { fs = System.IO.File.Open(tmpfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); fileSize = fs.Length; uniqueFileName = Path.GetFileName(fs.Name); using (BinaryReader br = new BinaryReader(fs)) { byte[] buffer = new byte[blockSize]; byte[] lastBuffer = null; long fileoffset = 0; long totalBytesRead = 0; int bytesRead; bool first = true; bool last = false; while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead = totalBytesRead + bytesRead; if (totalBytesRead >= fileSize) { last = true; lastBuffer = new byte[bytesRead]; Array.Copy(buffer, 0, lastBuffer, 0, bytesRead); } if (first) { using (MemoryStream contentStream = new MemoryStream()) { newFile.ContentStream = contentStream; newFile.Url = uniqueFileName; newFile.Overwrite = true; if (doc.foldername == null) { uploadFile = list.RootFolder.Files.Add(newFile); } /*else * { * string foldername = doc.foldername; * string sitecontent = doc.sitecontent; * * //Folder folder = list.RootFolder.Folders.GetByUrl(foldername); * * Folder folder = GetFolder(cc, list, foldername); * if (folder == null){ * if(doc.taxFields != null){ * folder = CreateDocumentSetWithTaxonomy(cc, list, sitecontent, foldername, doc.fields, fields, doc.taxFields); * } * else * { * folder = CreateFolder(cc, list, sitecontent, foldername, doc.fields, fields); * } * * } * }*/ using (MemoryStream s = new MemoryStream(buffer)) { bytesUploaded = uploadFile.StartUpload(uploadId, s); cc.ExecuteQuery(); fileoffset = bytesUploaded.Value; } first = false; } } else { uploadFile = cc.Web.GetFileByServerRelativeUrl(list.RootFolder.ServerRelativeUrl + Path.AltDirectorySeparatorChar + uniqueFileName); if (last) { using (MemoryStream s = new MemoryStream(lastBuffer)) { uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s); cc.ExecuteQuery(); } } else { using (MemoryStream s = new MemoryStream(buffer)) { bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s); cc.ExecuteQuery(); fileoffset = bytesUploaded.Value; } } } } } } finally { System.IO.File.Delete(tmpfile); if (fs != null) { fs.Dispose(); } } } else { System.IO.File.Delete(tmpfile); return(null); } return(uploadFile); } }
public static FileCreationInformation GetFileCreationInformation(string fileurl, string filename, SMBCredential SMBCredential, SMB2Client client, NTStatus nts, ISMBFileStore fileStore) { //SMBLibrary.NTStatus actionStatus; FileCreationInformation newFile = new FileCreationInformation(); NTStatus status = nts; object handle; FileStatus fileStatus; //string path = fileurl; //string path = "Dokument/ARKIV/RUNSAL/23_02_2011/sz001!.PDF"; string tmpfile = Path.GetTempFileName(); status = fileStore.CreateFile(out handle, out fileStatus, fileurl, AccessMask.GENERIC_READ, 0, ShareAccess.Read, CreateDisposition.FILE_OPEN, CreateOptions.FILE_NON_DIRECTORY_FILE, null); if (status != NTStatus.STATUS_SUCCESS) { Console.WriteLine(status); return(null); } else { byte[] buf; var fs = new FileStream(tmpfile, FileMode.OpenOrCreate); var bw = new BinaryWriter(fs); int bufsz = 64 * 1000; int i = 0; do { status = fileStore.ReadFile(out buf, handle, i * bufsz, bufsz); if (status == NTStatus.STATUS_SUCCESS) { int n = buf.GetLength(0); bw.Write(buf, 0, n); if (n < bufsz) { break; } i++; } }while (status != NTStatus.STATUS_END_OF_FILE && i < 1000); if (status == NTStatus.STATUS_SUCCESS) { fileStore.CloseFile(handle); bw.Flush(); fs.Close(); fs = System.IO.File.OpenRead(tmpfile); //byte[] fileBytes = new byte[fs.Length]; //fs.Read(fileBytes, 0, fileBytes.Length); newFile.Overwrite = true; newFile.ContentStream = fs; //newFile.Content = fileBytes; newFile.Url = filename; } else { System.IO.File.Delete(tmpfile); return(null); } System.IO.File.Delete(tmpfile); } return(newFile); }
private SMBFileShare(SMB2Client client, ISMBFileStore fileStore) { this.client = client; this.fileStore = fileStore; }
public ISMBClient CreateClient(uint maxBufferSize) { var client = new SMB2Client(); return(client); }