public static void Connect() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); conn.Connect(); } }
public void VerifyListing(string host, string username, string password) { var ftpClient = new FtpClient(); ftpClient.Host = host; ftpClient.Credentials = new NetworkCredential(username, password); ftpClient.Connect(); var listing = ftpClient.GetListing(); Assert.IsNotNull(listing); }
public static void DeleteFile() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); conn.DeleteFile("/full/or/relative/path/to/file"); } }
static void Main(string[] args) { //args = new[] {@"c:\Users\Pz\Documents\dev\praettest.cfg"}; args = new[] {@"c:\Users\Pz\Documents\dev\sync.cfg"}; var configuration = ParseArgs(args); if (configuration == null) { PrintUsage(); } else { var trackedFilesPath = args[0]; try { var ftp = new FtpClient(trackedFilesPath, configuration); ftp.Synchronize(); } catch (Exception e) { if (!FtpClient.Handle(e)) throw; } } Console.WriteLine(""); Console.WriteLine("Press any key to quit..."); Console.ReadKey(); }
public static void SetWorkingDirectory() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); conn.SetWorkingDirectory("/full/or/relative/path"); } }
public static void CreateDirectory() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); conn.CreateDirectory("/test/path/that/should/be/created", true); } }
public static void UploadFile(string ftpHost, string username, string password, string filepathToUpload, string fileToWrite) { FtpClient chipbox = new FtpClient(); chipbox.Host = ftpHost; chipbox.Credentials = new NetworkCredential(username, password); Stream chipboxDosya = chipbox.OpenWrite(fileToWrite); FileStream dosya = new FileStream(filepathToUpload, FileMode.Open); try { int bufferSize = 8192; int readCount; byte[] buffer = new byte[bufferSize]; readCount = dosya.Read(buffer, 0, bufferSize); while (readCount > 0) { chipboxDosya.Write(buffer, 0, readCount); readCount = dosya.Read(buffer, 0, bufferSize); } } finally { dosya.Close(); chipboxDosya.Close(); } }
private static void Main(string[] args) { string hostAddress; string username; string password; Console.WriteLine("Reading login data..."); /* * Read the login data for the server from a text-file called "Login", * with the following structure: * * Server address * Username * Password * */ var loginData = File.ReadAllLines("Login"); hostAddress = loginData[0]; username = loginData[1]; password = loginData[2]; Console.WriteLine("Starting integration test..."); Console.WriteLine(); client = new FtpClient(new NetworkCredential(username, password)); CreateDirectoryTest(new Uri(new Uri(hostAddress), "/TestDirectory1")); DeleteDirectoryTest(new Uri(new Uri(hostAddress), "/TestDirectory1")); Console.WriteLine(); Console.WriteLine("Integration test finished."); Console.ReadLine(); }
public override void Dispose() { if (_ftp != null) { _ftp.Dispose(); _ftp = null; } }
public static void GetFileSize() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); Console.WriteLine("The file size is: {0}", conn.GetFileSize("/full/or/relative/path/to/file")); } }
public static void GetWorkingDirectory() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); Console.WriteLine("The working directory is: {0}", conn.GetWorkingDirectory()); } }
void DataRefresh() { try { if (TxtData.DataBase.SoapStaus) { FtpClient ftp = new FtpClient(TxtData.XMLConfigure.IpAddress); ftp.DownLoadLog(); if ( !PublicFunc.ReadCs8CLog(out date,out Txt)) { return; } if (date!=null &&Txt!=null) { DataView dv = new DataView(); dv.Table = new System.Data.DataTable("Sequen"); dv.Table.Columns.Add(); dv.Table.Columns.Add(); dv.Table.Rows.Clear(); TxtData.CS8CConfigure.ViewPackaging = CB_ViewPackaging.Checked; for (int i = Txt.Length - 1; i >= 0; i--) { if (Txt[i] != null && Txt[i].IndexOf("COM-PC:") < 0) { if (TxtData.CS8CConfigure.ViewPackaging) { if (Txt[i].IndexOf("USR:"******"日期"; gv.Columns[1].Caption = "报警信息"; } } } catch { } }
public void WindowsServerTest() { var ftpTestHost = GetTestHost("ftp", "win"); using (var ftpClient = new FtpClient(ftpTestHost.Uri, ftpTestHost.Credential)) { var i = ftpClient.ServerType; var s = ftpClient.StatEntries("/").ToArray(); } }
public static void GetHashAlgorithm() { using (FtpClient cl = new FtpClient()) { cl.Credentials = new NetworkCredential("user", "pass"); cl.Host = "some.ftpserver.on.the.internet.com"; Console.WriteLine("The server is using the following algorithm for computing hashes: {0}", cl.GetHashAlgorithm()); } }
public void FileZillaUnixServerTest() { var ftpTestHost = GetTestHost("ftp", "fzx"); using (var ftpClient = new FtpClient(ftpTestHost.Uri, ftpTestHost.Credential)) { var i = ftpClient.ServerType; var s = ftpClient.StatEntries("/").ToArray(); } }
public void TestIssue3() { var ftpClient = new FtpClient("anonymous", string.Empty, "ftp://ftp.mozilla.org"); var ftpListItems = ftpClient.GetListing("/"); Assert.IsNotNull(ftpListItems); Assert.IsTrue(ftpListItems.Any()); }
/// <summary> /// Get remote file. Only FTP supported at present /// </summary> /// <param name="file"></param> /// <param name="destination"></param> /// <returns></returns> public static bool DownloadFile(Uri file, string destination) { try { string[] userInfo = file.UserInfo.Split(new[] { ':' }); if (userInfo.Length != 2) { Logger.Warn("No login information in URL!"); return false; } using (var cl = new FtpClient(userInfo[0], userInfo[1], file.Host)) { string remoteFile = file.PathAndQuery; // Check for existence #warning DOESN'T SEEM TO WORK ON ALL SERVERS // if (!cl.FileExists(remoteFile)) // return false; long size = cl.GetFileSize(remoteFile); using (FtpDataStream chan = cl.OpenRead(remoteFile)) { using (var stream = new FileStream(destination, FileMode.Create)) { using (var writer = new BinaryWriter(stream)) { var buf = new byte[cl.ReceiveBufferSize]; int read; long total = 0; while ((read = chan.Read(buf, 0, buf.Length)) > 0) { total += read; writer.Write(buf, 0, read); Logger.DebugFormat("\rDownloaded: {0}/{1} {2:p2}", total, size, (total / (double)size)); } } } // when Dispose() is called on the chan object, the data channel // stream will automatically be closed } // when Dispose() is called on the cl object, a logout will // automatically be performed and the socket will be closed. } } catch (Exception e) { Logger.Warn("Exception downloading file:" + e.Message); return false; } return true; }
public static void ValidateCertificate() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); conn.EncryptionMode = FtpEncryptionMode.Explicit; conn.ValidateCertificate += new FtpSslValidation(OnValidateCertificate); conn.Connect(); } }
public static void Rename() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); // renaming a directory is dependant on the server! if you attempt it // and it fails it's not because System.Net.FtpClient has a bug! conn.Rename("/full/or/relative/path/to/src", "/full/or/relative/path/to/dest"); } }
public static void SetHashAlgorithm() { using (FtpClient cl = new FtpClient()) { cl.Credentials = new NetworkCredential("user", "pass"); cl.Host = "some.ftpserver.on.the.internet.com"; if (cl.HashAlgorithms.HasFlag(FtpHashAlgorithm.MD5)) cl.SetHashAlgorithm(FtpHashAlgorithm.MD5); } }
/// <summary> /// Example illustrating how to dereference a symbolic link /// in a file listing. You can also pass the FtpListOption.DerefLinks /// flag to GetListing() to have automatically done in which /// case the FtpListItem.LinkObject property will contain the /// FtpListItem representing the object the link points at. The /// LinkObject property will be null if there was a problem resolving /// the target. /// </summary> public static void DereferenceLinkExample() { using (FtpClient client = new FtpClient()) { client.Credentials = new NetworkCredential("user", "pass"); client.Host = "somehost"; // This propety controls the depth of recursion that // can be done before giving up on resolving the link. // You can set the value to -1 for infinite depth // however you are strongly discourage from doing so. // The default value is 20, the following line is // only to illustrate the existance of the property. // It's also possible to override this value as one // of the overloaded arguments to the DereferenceLink() method. client.MaximumDereferenceCount = 20; // Notice the FtpListOption.ForceList flag being passed. This is because // symbolic links are only supported in UNIX style listings. My personal // experience has been that in practice MLSD listings don't specify an object // as a link, but rather list the link as a regular file or directory // accordingly. This may not always be the case however that's what I've // observed over the life of this project so if you run across the contrary // please report it. The specification for MLSD does include links so it's // possible some FTP server implementations do include links in the MLSD listing. foreach (FtpListItem item in client.GetListing(null, FtpListOption.ForceList | FtpListOption.Modify)) { Console.WriteLine(item); // If you call DerefenceLink() on a FtpListItem.Type other // than Link a FtpException will be thrown. If you call the // method and the LinkTarget is null a FtpException will also // be thrown. if (item.Type == FtpFileSystemObjectType.Link && item.LinkTarget != null) { item.LinkObject = client.DereferenceLink(item); // The return value of DerefenceLink() will be null // if there was a problem. if (item.LinkObject != null) { Console.WriteLine(item.LinkObject); } } } // This example is similar except it uses the FtpListOption.DerefLinks // flag to have symbolic links automatically resolved. You must manually // specify this flag because of the added overhead with regards to resolving // the target of a link. foreach (FtpListItem item in client.GetListing(null, FtpListOption.ForceList | FtpListOption.Modify | FtpListOption.DerefLinks)) { Console.WriteLine(item); if (item.Type == FtpFileSystemObjectType.Link && item.LinkObject != null) { Console.WriteLine(item.LinkObject); } } } }
public void Connect() { if (client != null && client.IsConnected) return; client = new FtpClient(); client.Host = server; client.Credentials = new NetworkCredential(login, password); client.DataConnectionType = FtpDataConnectionType.PASV; client.Connect(); }
public static void Execute() { using (FtpClient conn = new FtpClient()) { FtpReply reply; conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); if (!(reply = conn.Execute("SITE CHMOD 640 FOO.TXT")).Success) { throw new FtpCommandException(reply); } } }
public Site( AddressBookEntry abEntry ) { this.addressBookEntry = abEntry; UriBuilder uriBuilder = new UriBuilder( "ftp", addressBookEntry.host ); this.uri = uriBuilder.Uri; this.cred = new NetworkCredential( addressBookEntry.userName, addressBookEntry.userPass ); this.map = new Dictionary<string, SiteEntry>(); this.ftp = new FtpClient( uri, cred ); }
public static void DeleteDirectory() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); // Remove the directory and all objects beneath it. The last parameter // forces System.Net.FtpClient to use LIST -a for getting a list of objects // beneath the specified directory. conn.DeleteDirectory("/path/to/directory", true, FtpListOption.AllFiles | FtpListOption.ForceList); } }
public Ftp2(string host, int port, string user, string password, string rootPath) { this.ftpUser = user; this.rootPath = rootPath; this.ftpClient = new FtpClient { Host = host, Port = port, Credentials = new NetworkCredential(user, password), }; }
public AppBuilder(string user, string pass, string domain, string pathToGame, string pathToSite) { this.pathToGame = pathToGame; this.pathToSite = pathToSite; this.streams = new List<Stream>(); this.client = new FtpClient(); client.Credentials = new System.Net.NetworkCredential(user, pass, domain); client.Host = domain; client.Connect(); }
public static void DeleteDirectory() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); if (conn.DirectoryExists("/full/or/relative/path")) { // do something } } }
public FTP(FTPAccount account) { Account = account; client = new FtpClient() { Host = Account.Host, Port = Account.Port, Credentials = new NetworkCredential(Account.Username, Account.Password) }; if (account.IsActive) { client.DataConnectionType = FtpDataConnectionType.AutoActive; } else { client.DataConnectionType = FtpDataConnectionType.AutoPassive; } if (account.Protocol == FTPProtocol.FTPS) { switch (Account.FTPSEncryption) { default: case FTPSEncryption.Explicit: client.EncryptionMode = FtpEncryptionMode.Explicit; break; case FTPSEncryption.Implicit: client.EncryptionMode = FtpEncryptionMode.Implicit; break; } client.DataConnectionEncryption = true; if (!string.IsNullOrEmpty(account.FTPSCertificateLocation) && File.Exists(account.FTPSCertificateLocation)) { X509Certificate cert = X509Certificate2.CreateFromSignedFile(Account.FTPSCertificateLocation); client.ClientCertificates.Add(cert); } else { client.ValidateCertificate += (FtpClient control, FtpSslValidationEventArgs e) => { if (e.PolicyErrors != SslPolicyErrors.None) { e.Accept = true; } }; } } }
public static void FileExists() { using (FtpClient conn = new FtpClient()) { conn.Host = "localhost"; conn.Credentials = new NetworkCredential("ftptest", "ftptest"); // The last parameter forces System.Net.FtpClient to use LIST -a // for getting a list of objects in the parent directory. if (conn.FileExists("/full/or/relative/path", FtpListOption.ForceList | FtpListOption.AllFiles)) { // dome something } } }
/// <summary> /// Get the full path of a given FTP Listing entry /// </summary> public static void CalculateFullFtpPath(this FtpListItem item, FtpClient client, string path, bool isVMS) { // EXIT IF NO DIR PATH PROVIDED if (path == null) { // check if the path is absolute if (IsAbsolutePath(item.Name)) { item.FullName = item.Name; item.Name = item.Name.GetFtpFileName(); } return; } // ONLY IF DIR PATH PROVIDED // if this is a vax/openvms file listing // there are no slashes in the path name if (isVMS) { item.FullName = path + item.Name; } else { //this.client.LogStatus(item.Name); // remove globbing/wildcard from path if (path.GetFtpFileName().Contains("*")) { path = path.GetFtpDirectoryName(); } if (item.Name != null) { // absolute path? then ignore the path input to this method. if (IsAbsolutePath(item.Name)) { item.FullName = item.Name; item.Name = item.Name.GetFtpFileName(); } else if (path != null) { item.FullName = path.GetFtpPath(item.Name); //.GetFtpPathWithoutGlob(); } else { client.LogStatus(FtpTraceLevel.Warn, "Couldn't determine the full path of this object: " + Environment.NewLine + item.ToString()); } } // if a link target is set and it doesn't include an absolute path // then try to resolve it. if (item.LinkTarget != null && !item.LinkTarget.StartsWith("/")) { if (item.LinkTarget.StartsWith("./")) { item.LinkTarget = path.GetFtpPath(item.LinkTarget.Remove(0, 2)).Trim(); } else { item.LinkTarget = path.GetFtpPath(item.LinkTarget).Trim(); } } } }
/// <summary> /// Parses IBM z/OS format listings /// </summary> /// <param name="client">The FTP client</param> /// <param name="record">A line from the listing</param> /// <returns>FtpListItem if the item is able to be parsed</returns> public static FtpListItem Parse(FtpClient client, string record, string path) { // Skip title line - all modes have one. // Also set zOSListingRealm to remember the mode we are in // "total nnnn" if (record.Contains("total")) { client.zOSListingRealm = FtpZOSListRealm.Unix; return(null); } // "Volume Unit Referred Ext Used Recfm Lrecl BlkSz Dsorg Dsname" if (record.Contains("Volume Unit")) { client.zOSListingRealm = FtpZOSListRealm.Dataset; return(null); } // " Name VV.MM Created Changed Size Init Mod Id" if (record.Contains("Name VV.MM")) { // This is an opportunity to issue XDSS and get the LRECL, but how? FtpReply reply; string cwd; // Is caller using FtpListOption.NoPath and CWD to the right place? if (path.Length == 0) { cwd = client.GetWorkingDirectory(); } // Caller is not using FtpListOption.NoPath, so the path can be used // but needs modification depending on its ending. Remove the "(...)" else if (path.EndsWith(")'")) { cwd = path.Substring(0, path.IndexOf('(')) + "\'"; } else if (path.EndsWith(")")) { cwd = path.Substring(0, path.IndexOf('(')); } else { cwd = path; } if (!(reply = client.Execute("XDSS " + cwd)).Success) { throw new FtpCommandException(reply); } // SITE PDSTYPE=PDSE RECFM=FB BLKSIZE=16000 DIRECTORY=1 LRECL=80 PRIMARY=3 SECONDARY=110 TRACKS EATTR=SYSTEM string[] words = reply.Message.Split(' '); string[] val = words[5].Split('='); client.zOSListingLRECL = UInt16.Parse(val[1]); client.zOSListingRealm = FtpZOSListRealm.Member; return(null); } // "Name Size TTR Alias-of AC--------- Attributes--------- Amode Rmode" if (record.Contains("Name Size TTR")) { client.zOSListingRealm = FtpZOSListRealm.MemberU; return(null); } if (client.zOSListingRealm == FtpZOSListRealm.Unix) { // unix mode // //total 320 // return(FtpUnixParser.Parse(client, record)); } if (client.zOSListingRealm == FtpZOSListRealm.Dataset) { // PS/PO mode // //Volume Unit Referred Ext Used Recfm Lrecl BlkSz Dsorg Dsname //ANSYBG 3390 2020/01/03 1 15 VB 32756 32760 PS $.ADATA.XAA // // Ignore title line AND also ignore "VSAM", "Not Mounted" and "Error determining attributes" if (record.Substring(51, 4).Trim() == "PO" || record.Substring(51, 4).Trim() == "PS") { string volume = record.Substring(0, 6); string unit = record.Substring(7, 4); string referred = record.Substring(14, 10).Trim(); string ext = record.Substring(25, 2).Trim(); string used = record.Substring(27, 5).Trim(); string recfm = record.Substring(34, 4).Trim(); string lrecl = record.Substring(39, 5).Trim(); string blksz = record.Substring(45, 5).Trim(); string dsorg = record.Substring(51, 4).Trim(); string dsname = record.Remove(0, 56).Trim().Split(' ')[0]; bool isDir = dsorg == "PO"; var lastModifiedStr = referred; if (lastModifiedStr != "**NONE**") { lastModifiedStr += " 00:00"; } var lastModified = ParseDateTime(client, lastModifiedStr); var size = long.Parse(used) * 56664; // 3390 dev bytes per track var file = new FtpListItem(record, dsname, size, isDir, ref lastModified); return(file); } return(null); } if (client.zOSListingRealm == FtpZOSListRealm.Member) { // Member mode // // Name VV.MM Created Changed Size Init Mod Id //$2CPF1 01.01 2001/10/18 2001/10/18 11:58 29 29 0 QFX3076 // string name = record.Substring(0, 8).Trim(); string changed = string.Empty; string records = "0"; // Member stats may be empty if (record.TrimEnd().Length > 8) { string vvmm = record.Substring(10, 5).Trim(); string created = record.Substring(17, 10).Trim(); changed = record.Substring(27, 16).Trim(); records = record.Substring(44, 5).Trim(); string init = record.Substring(50, 5).Trim(); string mod = record.Substring(56, 5).Trim(); string id = record.Substring(62, 6).Trim(); } bool isDir = false; var lastModifiedStr = changed; var lastModified = ParseDateTime(client, lastModifiedStr); var size = ushort.Parse(records) * client.zOSListingLRECL; var file = new FtpListItem(record, name, size, isDir, ref lastModified); return(file); } if (client.zOSListingRealm == FtpZOSListRealm.MemberU) { // Member Loadlib mode // // Name Size TTR Alias-of AC --------- Attributes --------- Amode Rmode //EAGKCPT 000058 000009 00 FO RN RU 31 ANY //EAGRTPRC 005F48 000011 EAGRTALT 00 FO RN RU 31 ANY // string name = record.Substring(0, 8).Trim(); string changed = string.Empty; string memsize = record.Substring(10, 6); string TTR = record.Substring(19, 6); string Alias = record.Substring(26, 8).Trim(); string Attributes = record.Substring(38, 30); string Amode = record.Substring(70, 2); string Rmode = record.Substring(76, 3); bool isDir = false; var lastModifiedStr = changed; var lastModified = ParseDateTime(client, lastModifiedStr); var size = int.Parse(memsize, System.Globalization.NumberStyles.HexNumber); var file = new FtpListItem(record, name, size, isDir, ref lastModified); return(file); } return(null); }
public override async Task <JobResult> Execute(SqlService sql, AppSettings settings) { var srcPath = settings.PathForArchive(Src); var destHash = (await sql.DownloadStateByPrimaryKey(DestPK)).Hash; var destPath = settings.PathForArchive(destHash); if (Src == destHash) { return(JobResult.Success()); } Utils.Log($"Creating Patch ({Src} -> {DestPK})"); var cdnPath = CdnPath(Src, destHash); cdnPath.Parent.CreateDirectory(); if (cdnPath.Exists) { return(JobResult.Success()); } Utils.Log($"Calculating Patch ({Src} -> {DestPK})"); await using var fs = cdnPath.Create(); await using (var srcStream = srcPath.OpenRead()) await using (var destStream = destPath.OpenRead()) await using (var sigStream = cdnPath.WithExtension(Consts.OctoSig).Create()) { OctoDiff.Create(destStream, srcStream, sigStream, fs); } fs.Position = 0; Utils.Log($"Uploading Patch ({Src} -> {DestPK})"); int retries = 0; if (settings.BunnyCDN_User == "TEST" && settings.BunnyCDN_Password == "TEST") { return(JobResult.Success()); } TOP: using (var client = new FtpClient("storage.bunnycdn.com")) { client.Credentials = new NetworkCredential(settings.BunnyCDN_User, settings.BunnyCDN_Password); await client.ConnectAsync(); try { await client.UploadAsync(fs, $"updates/{Src.ToHex()}_{destHash.ToHex()}", progress : new UploadToCDN.Progress(cdnPath.FileName)); } catch (Exception ex) { if (retries > 10) { throw; } Utils.Log(ex.ToString()); Utils.Log("Retrying FTP Upload"); retries++; goto TOP; } } return(JobResult.Success()); }
/// <summary> /// Creates a new <see cref="FtpReader"/>. /// </summary> public FtpReader() { m_client = new FtpClient(true); }
public bool AddProduct(Product p, string imageName) { bool success = false; string categoryName = p.CategoryName; //Add image to FTP FtpClient clientFTP = new FtpClient("www.liquorlake.com"); //FTP credentials clientFTP.Credentials = new NetworkCredential("raybains", "PsiStorm1"); clientFTP.Connect(); clientFTP.RetryAttempts = 3; clientFTP.UploadFile(p.ImageUrl, "/httpdocs/Images/" + categoryName + "/" + imageName); p.ImageUrl = imageName; SqlConnection liquorLakeConn = new SqlConnection { ConnectionString = ConfigurationManager.ConnectionStrings["LiquorLakeConnection"].ConnectionString }; liquorLakeConn.Open(); SqlCommand addProductCMD = new SqlCommand() { CommandText = "AddProduct", CommandType = CommandType.StoredProcedure, Connection = liquorLakeConn }; SqlParameter addProductParam = new SqlParameter() { ParameterName = "@UPC", SqlDbType = SqlDbType.VarChar, SqlValue = p.UPC, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@CategoryID", SqlDbType = SqlDbType.VarChar, SqlValue = p.CategoryID, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@Name", SqlDbType = SqlDbType.VarChar, SqlValue = p.Name, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@Price", SqlDbType = SqlDbType.VarChar, SqlValue = p.Price, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@Size", SqlDbType = SqlDbType.VarChar, SqlValue = p.Size, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@CountryOfOrigin", SqlDbType = SqlDbType.VarChar, SqlValue = p.CountryOfOrigin, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@WineSweetnessIndex", SqlDbType = SqlDbType.VarChar, SqlValue = p.WineSweetnessIndex, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@Image", SqlDbType = SqlDbType.VarChar, SqlValue = p.ImageUrl, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@Company", SqlDbType = SqlDbType.VarChar, SqlValue = p.Company, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductParam = new SqlParameter() { ParameterName = "@Description", SqlDbType = SqlDbType.VarChar, SqlValue = p.Description, Direction = ParameterDirection.Input }; addProductCMD.Parameters.Add(addProductParam); addProductCMD.ExecuteNonQuery(); success = true; return(success); }
public static void TYPE(this FtpClient client, char type) => client.Send("TYPE {0}", type);
static public void LoadRazorAssemblies() { if (!_loadDone) { try { //Force the load of the assemblies if (dummy == null) { dummy = new HtmlString(""); } if (dummy2 == null) { dummy2 = new DataTable(); dummy2.AsEnumerable(); } if (dummy3 == null) { dummy3 = new OleDbConnection(); } if (dummy4 == null) { dummy4 = new LdapConnection(""); } if (dummy5 == null) { dummy5 = new SyndicationFeed(); } if (dummy6 == null) { dummy6 = new XDocument(); } if (dummy8 == null) { dummy8 = new PrincipalContext(ContextType.Machine); } if (dummy9 == null) { dummy9 = JWT.DefaultSettings; } if (dummy10 == null) { dummy10 = JObject.Parse("{}"); } if (dummy11 == null) { dummy11 = new FastZip(); } if (dummy12 == null) { dummy12 = new OdbcConnection(); } if (dummy13 == null) { dummy13 = new SqlConnection(); } if (dummy14 == null) { dummy14 = new SftpClient("", "a", ""); } if (dummy15 == null) { dummy15 = new FtpClient(); } if (dummy16 == null) { dummy16 = new HttpClient(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } _loadDone = true; } }
public static void SYST(this FtpClient client) => client.Send("SYST");
public static void FEAT(this FtpClient client) => client.Send("FEAT");
public static void RETR(this FtpClient client, string fileName) => client.Send("RETR {0}", fileName);
public static void STOR(this FtpClient client, string filename) => client.Send("STOR {0}", filename);
public static void PWD(this FtpClient client) => client.Send("PWD");
public static void MODE(this FtpClient client, char mode) => client.Send("MODE {0}", mode);
public static void STRU(this FtpClient client, char type) => client.Send("STRU {0}", type);
private static void Client_ValidateCertificate(FtpClient control, FtpSslValidationEventArgs e) { e.Accept = true; }
public static void PASV(this FtpClient client) => client.Send("PASV");
protected override bool _Run() { try { string address = Authentication.NextAddress(ServerAddress); if (address == null) { Exception ex = new Exception("No valid address. (" + ServerAddress + ")"); Exceptions.Add(ex); AppendToMessage(ex.Message); return(false); } Surge.FailureAction tgtAction = FileNotExistsAction; FtpClient conn = Authentication.OpenClient(address, Int32.Parse(Port)); try { if (conn.FileExists(Authentication.AdjustPath(address, FileName))) { tgtAction = FileExistsAction; } switch (tgtAction) { case Surge.FailureAction.SkipRemaining: SkipRemaining(); break; case Surge.FailureAction.SkipNext: SkipNext(); break; case Surge.FailureAction.Rollback: RollbackAllPreceedingAndSkipRemaining(); break; case Surge.FailureAction.Continue: break; case Surge.FailureAction.SkipToLabel: SkipForwardToFlowControlLabel(TargetLabel); break; } } finally { Authentication.RecycleClient(conn); } } catch (Exception ex) { AppendToMessage(ex.Message); Exceptions.Add(ex); } return(Exceptions.Count == 0); }
public static void NOOP(this FtpClient client) => client.Send("NOOP");
private void RbnSave_Click(object sender, EventArgs e) { //throw new NotImplementedException(); bc.cStf.staff_id = ""; FrmPasswordConfirm frm = new FrmPasswordConfirm(bc); frm.ShowDialog(this); if (!bc.cStf.staff_id.Equals("")) { String filename = "", ext = ""; if (!Directory.Exists("medical")) { Directory.CreateDirectory("medical"); } filename = "medical\\" + hn + "_" + bc.vsdate + "_" + bc.preno + "_" + status + ".rtf"; SaveDocumentMedicalExamination(filename); Application.DoEvents(); Thread.Sleep(200); if (File.Exists(filename)) { ext = Path.GetExtension(filename); FtpClient ftp = new FtpClient(bc.iniC.hostFTP, bc.iniC.userFTP, bc.iniC.passFTP, bc.ftpUsePassive); DocScan dsc = new DocScan(); dsc.active = "1"; dsc.doc_scan_id = ""; dsc.doc_group_id = ""; dsc.hn = bc.hn; //dsc.vn = dt.Rows[0]["MNC_VN_NO"].ToString() + "/" + dt.Rows[0]["MNC_VN_SEQ"].ToString() + "(" + dt.Rows[0]["MNC_VN_SUM"].ToString() + ")"; dsc.an = ""; dsc.visit_date = bc.vsdate; dsc.host_ftp = bc.iniC.hostFTP; //dsc.image_path = txtHn.Text + "//" + txtHn.Text + "_" + dgssid + "_" + dsc.row_no + "." + ext[ext.Length - 1]; dsc.image_path = ""; dsc.doc_group_sub_id = ""; dsc.pre_no = bc.preno; dsc.folder_ftp = bc.iniC.folderFTP; // dsc.status_ipd = chkIPD.Checked ? "I" : "O"; dsc.row_no = "1"; dsc.row_cnt = "1"; dsc.status_version = "2"; dsc.req_id = ""; dsc.date_req = ""; dsc.status_ipd = "0"; //dsc.ml_fm = "FM-LAB-999"; if (status.Equals("cc")) { dsc.ml_fm = "FM-MED-900"; // } else if (status.Equals("me")) { dsc.ml_fm = "FM-MED-901"; // } else if (status.Equals("diag")) { dsc.ml_fm = "FM-MED-902"; // } bc.bcDB.dscDB.voidDocScanByStatusMedicalExamination(hn, dsc.ml_fm, bc.vsdate, bc.preno, bc.cStf.staff_id); dsc.patient_fullname = ptt.Name; dsc.status_record = "5"; // status medical diagnose dsc.comp_labout_id = ""; String re = bc.bcDB.dscDB.insertMedicalExamination(dsc, bc.userId); dsc.image_path = hn + "//" + status + "_" + bc.hn + "_" + bc.vsdate + "_" + bc.preno + "_" + re + ext; String re1 = bc.bcDB.dscDB.updateImagepath(dsc.image_path, re); ftp.createDirectory(bc.iniC.folderFTP + "//" + hn.Replace("/", "-")); // สร้าง Folder HN ftp.delete(bc.iniC.folderFTP + "//" + dsc.image_path); Thread.Sleep(200); if (ftp.upload(bc.iniC.folderFTP + "//" + dsc.image_path, filename)) { } } } }
public static void QUIT(this FtpClient client) => client.Send("QUIT");
void ListDirectory(string server, int port, List <FtpListItem> ftpListItems, List <string> directoriesListed, string directory, FTPListType listType, bool recurse, Regex exclusiveDirectoryFilters, Regex inclusiveDirectoryFilters, Regex exclusiveFileFilters, Regex inclusiveFileFilters) { FtpClient conn = OpenClient(server, port); try { foreach (FtpListItem i in conn.GetListing(directory, FtpListOption.Modify | FtpListOption.Size | FtpListOption.DerefLinks | FtpListOption.AllFiles)) { switch (i.Type) { case FtpFileSystemObjectType.Directory: if (exclusiveDirectoryFilters != null && exclusiveDirectoryFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.FullName).ToUpper())) { continue; } if (inclusiveDirectoryFilters != null && !inclusiveDirectoryFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.FullName).ToUpper())) { continue; } if (listType == FTPListType.Directory || listType == FTPListType.All) { ftpListItems.Add(i); } if (recurse && !directoriesListed.Contains(i.FullName)) { directoriesListed.Add(i.FullName); ListDirectory(server, port, ftpListItems, directoriesListed, i.FullName, listType, recurse, exclusiveDirectoryFilters, inclusiveDirectoryFilters, exclusiveFileFilters, inclusiveFileFilters); } break; case FtpFileSystemObjectType.File: if (listType == FTPListType.File || listType == FTPListType.All) { if (exclusiveFileFilters != null && exclusiveFileFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.FullName).ToUpper())) { continue; } if (inclusiveFileFilters != null && !inclusiveFileFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.FullName).ToUpper())) { continue; } ftpListItems.Add(i); } break; case FtpFileSystemObjectType.Link: if (i.LinkObject != null) { switch (i.LinkObject.Type) { case FtpFileSystemObjectType.Directory: if (exclusiveDirectoryFilters != null && exclusiveDirectoryFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.LinkObject.FullName).ToUpper())) { continue; } if (inclusiveDirectoryFilters != null && !inclusiveDirectoryFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.LinkObject.FullName).ToUpper())) { continue; } if (listType == FTPListType.Directory || listType == FTPListType.All) { ftpListItems.Add(i.LinkObject); } if (recurse && !directoriesListed.Contains(i.LinkObject.FullName)) { directoriesListed.Add(i.LinkObject.FullName); ListDirectory(server, port, ftpListItems, directoriesListed, i.LinkObject.FullName, listType, recurse, exclusiveDirectoryFilters, inclusiveDirectoryFilters, exclusiveFileFilters, inclusiveFileFilters); } break; case FtpFileSystemObjectType.File: if (listType == FTPListType.File || listType == FTPListType.All) { if (exclusiveFileFilters != null && exclusiveFileFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.LinkObject.FullName).ToUpper())) { continue; } if (inclusiveFileFilters != null && !inclusiveFileFilters.IsMatch(STEM.Sys.IO.Path.GetFileName(i.LinkObject.FullName).ToUpper())) { continue; } ftpListItems.Add(i.LinkObject); } break; } } break; } } } finally { RecycleClient(conn); } }
public static void NLST(this FtpClient client, string directory = null) => client.Send(string.Format("NLST {0}", directory ?? string.Empty).TrimEnd());
public void Brute() { Thread currThread = Thread.CurrentThread; string credDetails = ""; int startime = DateTime.Now.Millisecond; // System.Timers.Timer aTimer = new System.Timers.Timer(); // aTimer.Elapsed += delegate (object sender, ElapsedEventArgs elapsed) { onTimedEvent(sender, elapsed, currThread); }; // aTimer.AutoReset = true; while (!foundLogin) { string pwd_num = pwd_first(501, 501).ToString(); string pwd_chr = pwd_second(3).ToString(); var pwd = pwd_num + pwd_chr; // aTimer.Enabled = true; FtpClient ftp = new FtpClient(srv, usr, pwd); try { ftp.Login(); int endtime = DateTime.Now.Millisecond; int totalTime = startime - endtime; elapsed(totalTime, currThread); } catch (FtpClient.FtpException returncode) { switch (returncode.Message) { case "530": attempts += 1; Console.Write("\r({0}) | Attempts: {1}", Thread.CurrentThread.Name.ToString(), attempts + " "); break; case "230": Console.Write("\rSuccessfully acquired login details after {0} attempts, Saving [+]", attempts); credDetails = "ftp://" + srv + "::" + usr + "::" + pwd; foundLogin = true; break; } } } Console.WriteLine("\n"); Console.WriteLine("((" + Thread.CurrentThread.Name.ToString() + "))" + "((" + credDetails + "))"); var path = (Directory.GetCurrentDirectory() + @"\" + usr + ".txt"); File.WriteAllText(path, credDetails); Environment.Exit(1); }
public static void ABOR(this FtpClient client) => client.Send("ABOR");
private void addStudentBtn_Click(object sender, EventArgs e) //Event handler for when the Add Student button is clicked { string className; //Instantiates the class name string studentID = pinBox.Text; //initialises the student ID to be added and the username to be added string userName = "******"; if (listBox1.SelectedItem != null) //Ensures a class name has been selected { FtpClient clientFTP = new FtpClient(); clientFTP.Host = "ftp://127.0.0.1"; clientFTP.Port = 54443; clientFTP.Credentials.UserName = "******"; clientFTP.Credentials.Password = "******"; clientFTP.DataConnectionReadTimeout = 2147483645; clientFTP.ConnectTimeout = 2147483645; clientFTP.DataConnectionConnectTimeout = 2147483645; clientFTP.ReadTimeout = 2147483645; string ConnectionString = "Server=127.0.0.1;Database=prototypedatabase;Uid=Killian;Pwd=blackrock;"; //MySQL Connection string using (MySqlConnection con = new MySqlConnection(ConnectionString)) //Scope for the MySQL commands { con.Open(); MySqlCommand cmd = con.CreateCommand(); cmd.CommandText = @"select count(*) from userpass where idUser=@studentID"; //Query used to obtain the number of students with the same user ID cmd.Parameters.Add(new MySqlParameter("studentID", studentID)); int i = Convert.ToInt32(cmd.ExecuteScalar()); //Assigns the variable i to the output/result of the MySQL query if (i > 0) //If a user exists with the user ID { cmd.CommandText = @"select UserName from prototypedatabase.userpass where idUser=@studentID"; //Another command query, obtains the user name of the user with matching user ID userName = cmd.ExecuteScalar().ToString(); //Assigns the user name to the variable userName StringBuilder csvContent = new StringBuilder(); //Creates a StringBuilder object csvContent.Append($"{studentID}, {userName}"); //Appends this StringBuilder object with the content obtained from the MySQL queries string csvPath = Path.GetTempPath() + "tempcsv.csv"; //Creates a temporary CSV file File.AppendAllText(csvPath, csvContent.ToString()); //Inserts this StringBuilder object's contents to the csv foreach (FtpListItem item in clientFTP.GetListing($@"Classes/{Global.currentUser}")) //Runs through the directory of the teacher for comparisons { if (listBox1.SelectedItem.ToString() == item.FullName) //Finds the matching directory of the one where a student is to be added { className = item.Name; if (!(clientFTP.FileExists($@"\Classes\{ Global.currentUser}\{className}\{userName}.csv"))) //Checks that the student hasnt already been added to the class { clientFTP.UploadFile(csvPath, $@"\Classes\{Global.currentUser}\{className}\{userName}.csv"); //If not, then adds student CSV file to teacher's directory under the name of the students user name MessageBox.Show("Success, student added!"); //Informs the user that the student was successfully added ListDirectory(); //Refresh of the first list box } else //Otherwise { MessageBox.Show("Student already added to this class"); //Informs the user that the student already exists in this class } } } clientFTP.Disconnect(); File.Delete(csvPath); //Deletes temporary CSV file } else //Otherwise { MessageBox.Show("No student exists with this ID"); //Informs the user that the student does not exist } } } else //Otherwise { MessageBox.Show("Please select a class"); //Informs user to select a class in the first list box } }
public static void MKD(FtpClient client, string name) => client.Send("MKD {0}", name);
private void ContextMenu_upload(object sender, System.EventArgs e) { String dgs = "", filename = "", id = ""; filename = searchInArray(); if (txtHn.Text.Equals("")) { MessageBox.Show("กรุณาป้อน HN", ""); return; } try { filename = filename.Substring(filename.IndexOf('*') + 1); //String[] ext = filename.Split('.'); string ext = Path.GetExtension(filename); String dgssname = "", dgssid = ""; dgssname = ((MenuItem)sender).Text; dgssid = ic.ivfDB.dgssDB.getIdDgss(dgssname); DocGroupSubScan dgss = new DocGroupSubScan(); dgss = ic.ivfDB.dgssDB.selectByPk(dgssid); if (!dgss.doc_group_sub_id.Equals("")) { //dgs = cboDgs.SelectedItem == null ? "" : ((ComboBoxItem)cboDgs.SelectedItem).Value; int row = 0, col = 0; row = grf.Row; col = grf.Col; DocScan dsc = new DocScan(); dsc.active = "1"; dsc.doc_scan_id = ""; dsc.doc_group_id = dgss.doc_group_id; dsc.hn = txtHn.Text; dsc.vn = txtVN.Text; dsc.an = ""; dsc.visit_date = ic.datetoDB(txtVisitDate.Text); //if (!txtVN.Text.Equals("")) //{ // dsc.row_no = bc.ivfDB.dscDB.selectRowNoByHnVn(txtHn.Text, txtVN.Text, dgs); //} //else //{ // dsc.row_no = bc.ivfDB.dscDB.selectRowNoByHn(txtHn.Text, dgs); //} dsc.host_ftp = ic.iniC.hostFTP; //dsc.image_path = txtHn.Text + "//" + txtHn.Text + "_" + dgssid + "_" + dsc.row_no + "." + ext[ext.Length - 1]; dsc.image_path = ""; dsc.doc_group_sub_id = dgssid; dsc.pre_no = ""; dsc.an = ""; DateTime dt = new DateTime(); dsc.an_date = ""; //if (dsc.an_date.Equals("1-01-01")) //{ // dsc.an_date = ""; //} dsc.status_ipd = "O"; dsc.folder_ftp = ic.iniC.folderFTP; String re = ic.ivfDB.dscDB.insertDocScan(dsc, ic.userId); dsc.image_path = txtVN.Text + "//" + txtHn.Text.Replace("/", "-") + "_" + txtVN.Text + "_" + re + ext; String re1 = ic.ivfDB.dscDB.updateImagepath(dsc.image_path, re); FtpClient ftp = new FtpClient(ic.iniC.hostFTP, ic.iniC.userFTP, ic.iniC.passFTP, ic.ftpUsePassive, ic.iniC.pathChar); //MessageBox.Show("111", ""); ftp.createDirectory(ic.iniC.folderFTP + "//" + txtVN.Text); //MessageBox.Show("222", ""); ftp.delete(dsc.image_path); //MessageBox.Show("333", ""); ftp.upload(ic.iniC.folderFTP + "//" + dsc.image_path, filename); Boolean findTrue = false; foreach (Control con in this.Controls) { if (findTrue) { break; } if (con is Panel) { foreach (Control conp in con.Controls) { if (findTrue) { break; } if (conp is C1DockingTab) { foreach (Control cond in conp.Controls) { if (findTrue) { break; } if (cond is C1DockingTabPage) { foreach (Control cong in cond.Controls) { if (findTrue) { break; } if (cong is C1DockingTab) { foreach (Control congd in cong.Controls) { if (findTrue) { break; } if (congd is C1DockingTabPage) { foreach (Control congd1 in congd.Controls) { if (findTrue) { break; } if (congd1 is C1FlexGrid) { if (congd1.Name.Equals(dsc.doc_group_sub_id)) { String aa = ""; C1FlexGrid grf1; grf1 = (C1FlexGrid)congd1; Row rowg = grf1.Rows.Add(); Image loadedImage, resizedImage; loadedImage = Image.FromFile(filename); int originalWidth = 0; originalWidth = loadedImage.Width; int newWidth = 280; resizedImage = loadedImage.GetThumbnailImage(newWidth, (newWidth * loadedImage.Height) / originalWidth, null, IntPtr.Zero); // rowg[colPic1] = resizedImage; rowg[colPic2] = filename; //grf[grf.Row, grf.Col] = dsc.doc_group_sub_id; grf1.AutoSizeRows(); Application.DoEvents(); addInArrayImg(filename, dsc.doc_group_sub_id); grf.SetData(grf.Row, grf.Col, dgssname); grf.AutoSizeRows(grf.Row, grf.Col, grf.Row, grf.Col, 20, AutoSizeFlags.SameSize); findTrue = true; break; } } } } } } } } } } } } } //grf.AutoSizeRows(); //grf.AutoSizeCols(); //CellRange cr = grf.GetCellRange(grf.Row, grf.Col); CellStyle cs = grf.Styles.Add("CellNeWStyle"); cs.BackColor = Color.Green; cs.Border.Color = Color.FromArgb(196, 228, 223); cs.Border.Color = Color.Black; //cr.Style = cs; grf.SetCellStyle(grf.Row, grf.Col, cs); grf.Styles.Normal.ImageAlign = C1.Win.C1FlexGrid.ImageAlignEnum.CenterTop; grf.Styles.Normal.TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.CenterBottom; grf.SetData(grf.Row, grf.Col, dgssname); } } catch (Exception ex) { } }
public static void CWD(this FtpClient client, string directory) => client.Send("CWD {0}", directory);
public static void PASS(this FtpClient client, string password) => client.Send("PASS {0}", password);
public static void USER(this FtpClient client, string username) => client.Send("USER {0}", username);