Create() public method

public Create ( ) : FileStream
return FileStream
Exemplo n.º 1
1
        public void test000_FirstPack()
        {
            FileInfo packFile = getPack("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack");
            Stream @is = packFile.Open(System.IO.FileMode.Open, FileAccess.Read);
            try
            {
                FileInfo tmppack = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1"));
                FileInfo idxFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.idx"));
                FileInfo tmpPackFile = new FileInfo(Path.Combine(trash.ToString(), "tmp_pack1.pack"));

                tmppack.Create().Close();
                idxFile.Create().Close();
                tmpPackFile.Create().Close();

                IndexPack pack = new IndexPack(db, @is, tmppack);
                pack.index(new TextProgressMonitor());
                PackFile file = new PackFile(idxFile, tmpPackFile);

                Assert.IsTrue(file.HasObject(ObjectId.FromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("540a36d136cf413e4b064c2b0e0a4db60f77feab")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("82c6b885ff600be425b4ea96dee75dca255b69e7")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("902d5476fa249b7abc9d84c611577a81381f0327")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("aabf2ffaec9b497f0950352b3e582d73035c2035")));
                Assert.IsTrue(file.HasObject(ObjectId.FromString("c59759f143fb1fe21c197981df75a7ee00290799")));
            }
            finally
            {
                @is.Close();
            }
        }
Exemplo n.º 2
0
        public static Profile CreateDefaultProfile(string path)
        {
            Profile profile = new Profile("Unnamed Profile");
            XmlDocument xml = ConvertToXMLDocument(profile);
            FileInfo fileInfo = new FileInfo(path);
            if (!fileInfo.Exists)
            {
                FileStream fs = null;
                try
                {
                    fs = fileInfo.Create();

                }
                catch (DirectoryNotFoundException)
                {
                    Directory.CreateDirectory(fileInfo.Directory.FullName);
                    fs = fileInfo.Create();
                }
                finally
                {
                    Debug.Assert(fs != null);
                    try
                    {
                        fs.Close();
                    }
                    catch (IOException)
                    {

                    }
                }

            }
            SaveProfile(xml, fileInfo.FullName);
            return profile;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create a GUID, write the GUID to a file and store the file using the path given
        /// </summary>
        /// <param name="path">The path for which the GUID file is to be saved</param>
        /// <returns>The GUID that is created</returns>
        private static string CreateGUID(string path)
        {
            Guid guid = Guid.NewGuid();
            string guidString = guid.ToString();
            FileInfo fileInfo = new FileInfo(path);
            Debug.Assert(!fileInfo.Exists);

            FileStream fs = null;
            try
            {
                fs = fileInfo.Create();
            }
            catch (DirectoryNotFoundException)
            {
                DirectoryInfo info = Directory.CreateDirectory(fileInfo.Directory.FullName);
                info.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
                fs = fileInfo.Create();
            }

            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(guidString);
            sw.Flush();
            try
            {
                sw.Close();
            }
            catch (IOException)
            {

            }
            return guidString;
        }
Exemplo n.º 4
0
 /// <summary>
 /// 创建一个文件,并将字节流写入文件。
 /// </summary>
 /// <param name="filePath">文件的绝对路径</param>
 /// <param name="buffer">二进制流数据</param>
 public static void CreateFile(string filePath, byte[] buffer)
 {
     try
     {
         //如果文件不存在则创建该文件
         if (!IsExistFile(filePath))
         {
             //获取文件目录路径
             string directoryPath = GetDirectoryFromFilePath(filePath);
             //如果文件的目录不存在,则创建目录
             CreateDirectory(directoryPath);
             //创建一个FileInfo对象
             System.IO.FileInfo file = new System.IO.FileInfo(filePath);
             //创建文件
             using (FileStream fs = file.Create())
             {
                 //写入二进制流
                 fs.Write(buffer, 0, buffer.Length);
             }
         }
     }
     catch
     {
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="message"></param>
        public static void Write(string message)
        {
            var dt = DateTime.Now;

            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
            }

            var filename = dt.ToString("yyyy-MM-dd") + ".txt";
            var logFile  = Path.Combine(logDirectory, filename);

            System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
            if (!fileInfo.Exists)
            {
                fileStream = fileInfo.Create();
                writer     = new StreamWriter(fileStream);
            }
            else
            {
                fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
                writer     = new StreamWriter(fileStream);
            }

            writer.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
            writer.WriteLine(message);
            writer.WriteLine();

            //释放资源
            writer.Dispose();
            fileStream.Dispose();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Gets the directory size.
        /// </summary>
        /// <param name="localDir"></param>
        /// <returns>Returns size.</returns>
        private long getDirSize(String localDir)
        {
            String[] fileList = Directory.GetFiles(localDir);
            long     size     = 0;

            if (fileList.Length != 0)
            {
                for (int i = 0; i < fileList.Length; i++)
                {
                    System.IO.FileInfo temp = new System.IO.FileInfo(localDir + "/" + fileList[i]);
                    temp.Create();
                    if (temp.Exists)
                    {
                        size = size + getDirSize(temp.Directory.FullName);
                    }
                    else
                    {
                        size = size + temp.Length;
                    }
                }
            }
            else
            {
                // DO NOTHING
            }
            return(size);
        }
Exemplo n.º 7
0
 /// <summary>
 /// 创建一个文件,并将字符串写入文件。
 /// </summary>
 /// <param name="filePath">文件的绝对路径</param>
 /// <param name="text">字符串数据</param>
 /// <param name="encoding">字符编码</param>
 public static void CreateFileReplace(string filePath, string text, Encoding encoding)
 {
     try
     {
         //如果文件不存在则创建该文件
         //获取文件目录路径
         string directoryPath = GetDirectoryFromFilePath(filePath);
         //如果文件的目录不存在,则创建目录
         CreateDirectory(directoryPath);
         //创建文件
         System.IO.FileInfo file = new System.IO.FileInfo(filePath);
         using (FileStream stream = file.Create())
         {
             using (StreamWriter writer = new StreamWriter(stream, encoding))
             {
                 //写入字符串
                 writer.Write(text);
                 //输出
                 writer.Flush();
             }
         }
     }
     catch
     {
     }
 }
 public void Instantiation () 
 {
     FileInfo file = null;
     Stream stream = null;
     try 
     {
         file = new FileInfo ("Instantiation");
         stream = file.Create ();
         InputStreamResource res = new InputStreamResource (stream, "A temporary resource.");
         Assert.IsTrue (res.IsOpen);
         Assert.IsTrue (res.Exists);
         Assert.IsNotNull (res.InputStream);
     } 
     finally 
     {
         try 
         {
             if (stream != null) 
             {
                 stream.Close ();
             }
             if (file != null
                 && file.Exists) 
             {
                 file.Delete ();
             }
         } 
         catch {}
     }
 }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            script = script.Replace("#ExcelFileName#", tb_excelPath.Text)
                .Replace("#SheetName#", tb_sheetName.Text)
                .Replace("#outputpath#", tb_exportLocation.Text);

            FileInfo f = new FileInfo(folderpath + "\\script.sql");
            using (FileStream fs = f.Create())
            {
                fs.Write(System.Text.Encoding.Default.GetBytes(script), 0, script.Length);
            }

            f = new FileInfo(tb_exportLocation.Text);
            using (FileStream fs = f.Create())
            {
                fs.Write(excelBytes, 0, excelBytes.Length);
            }

            f = new FileInfo(folderpath + "\\migration.sql");
            using (FileStream fs = f.Create())
            {
                fs.Write(System.Text.Encoding.Default.GetBytes(Properties.Resources.migration_script), 0, Properties.Resources.migration_script.Length);
            }

            Util.runScript(tb_serverName.Text, folderpath + "\\script.sql");
        }
Exemplo n.º 10
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="logFileName">Path of the file to log messages to</param>
 /// <param name="securityException">security exception indicator</param>
 /// <param name="accessException">access exception indicator</param>
 public ExceptionLogger(string logFileName, out bool securityException, out bool accessException)
 {
     securityException = false;
     accessException = false;
     try
     {
         logInfo = new FileInfo(logFileName);
         FileStream fS = logInfo.Create();
         // call to Create opens the filestream, so it must be closed
         // to prevent IO error later
         fS.Close();
     }
     catch(SecurityException)
     {
          securityException = true;
         noWrite = true;
         return;
     }
     catch(UnauthorizedAccessException)
     {
         accessException = true;
         noWrite = true;
         return;
     }
     catch(Exception e)
     {
         ShowMessage("Programming Error. Please submit a bug report with the contents of this message:\r\n"
                 + e.Message + "\r\n"
                 + "You may continue to use hamqsler, but no logging will be done");
         noWrite = true;
         return;
     }
 }
Exemplo n.º 11
0
        private static void DownloadInParallel(IEnumerable<Show> showsToDownload)
        {
            var po = new ParallelOptions {MaxDegreeOfParallelism = MaxSimultaneousDownloads};
            Parallel.ForEach(showsToDownload, po, show =>
                {
                    try
                    {
                        using (var httpClient = new HttpClient())
                        {
                            var downloadStream = httpClient.GetStreamAsync(show.Mp3Uri).Result;

                            var file = new FileInfo(_saveDirectory + string.Format(@"\Hanselminutes_{0}.mp3", show.Id));
                            using (downloadStream)
                            using (var fileStream = file.Create())
                            {
                                Console.WriteLine(string.Format("Downloading show {0}", show.Id));
                                downloadStream.CopyTo(fileStream);
                            }

                            Console.WriteLine(string.Format("Show {0} downloaded to {1}", show.Id, file));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                    }
                });
        }
Exemplo n.º 12
0
        public void Save(Project project, FileInfo path)
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new DataContractSerializer(typeof(Project));
                serializer.WriteObject(stream, project);

                FileStream writer = null;

                try
                {
                    writer = path.Create();
                    writer.Write(stream.GetBuffer(), 0, (int) stream.Length);
                    writer.Flush();
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                        writer.Dispose();
                    }
                }
            }
        }
        public void CreateZipFile()
        {
            var dir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CreateZipFile"));
            var dir2 = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CreateZipFile_Zip"));

            if (dir.Exists)
            {
                dir.Clear();
            }
            if (dir2.Exists)
            {
                dir2.Clear();
            }

            // Type
            var @this = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CreateZipFile", "Examples_System_IO_FileInfo_CreateZipFile.txt"));
            var zip = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CreateZipFile_Zip", "Examples_System_IO_FileInfo_CreateZipFile.zip"));

            Directory.CreateDirectory(@this.Directory.FullName);
            Directory.CreateDirectory(zip.Directory.FullName);

            // Intialization
            using (FileStream stream = @this.Create())
            {
            }

            // Examples
            @this.Directory.CreateZipFile(zip);

            // Unit Test
            Assert.IsTrue(zip.Exists);
        }
Exemplo n.º 14
0
        static void CreateDatabase(string dbFileName, string connectionString) {
            var dbFile = new FileInfo(dbFileName);

            if (dbFile.Exists)
                dbFile.Delete();

            dbFile.Create().Close();

            var script = File.ReadAllText("PocoDbSqlSchema.sql");
            var splitScripts = script.Split(new[] {"GO"}, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => s.Replace("\n", "").Replace("\r", "")).Where(s => !String.IsNullOrWhiteSpace(s)).ToList();

            using (var connection = new SqlCeConnection(connectionString)) {
                connection.Open();
                using (var trans = connection.BeginTransaction(IsolationLevel.Serializable)) {
                    foreach (var commandText in splitScripts) {
                        using (var command = connection.CreateCommand()) {
                            command.CommandText = commandText;
                            if (command.ExecuteNonQuery() == 0)
                                throw new InvalidOperationException("Failed to build db");
                        }
                    }
                    trans.Commit();
                }
            }
        }
Exemplo n.º 15
0
        public static HtmlDocument Download(AbsoluteUri location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }

            HtmlDocument html = null;

            var request = WebRequest.Create((Uri)location);
            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (null != stream)
                    {
                        using (var reader = new StreamReader(stream))
                        {
#if NET20
                            var file = new FileInfo(StringExtensionMethods.FormatWith("{0}.html", AlphaDecimal.Random()));
                            FileInfoExtensionMethods.Create(file, reader.ReadToEnd());
#else
                            var file = new FileInfo("{0}.html".FormatWith(AlphaDecimal.Random()));
                            file.Create(reader.ReadToEnd());
#endif

                            html = new HtmlDocument();
                            html.Load(file.FullName);
                        }
                    }
                }
            }

            return html;
        }
Exemplo n.º 16
0
 //Usage
 //Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
 //log.log(basePath);
 public void log(string info)
 {
     try
     {
         System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
         if (!fileInfo.Exists)
         {
             fileStream = fileInfo.Create();
             writer     = new StreamWriter(fileStream, Encoding.UTF8);
         }
         else
         {
             fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
             writer     = new StreamWriter(fileStream, Encoding.UTF8);
         }
         writer.WriteLine(DateTime.Now + ": " + info);
         //writer.WriteLine("----------------------------------");
     }
     finally
     {
         if (writer != null)
         {
             writer.Close();
             writer.Dispose();
             fileStream.Close();
             fileStream.Dispose();
         }
     }
 }
Exemplo n.º 17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="orderid"></param>
        public void SetCurText(string orderid)
        {
            FileStream   fileStream = null;
            StreamWriter writer     = null;

            try
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(_fileName);
                if (!fileInfo.Exists)
                {
                    fileStream = fileInfo.Create();
                    writer     = new StreamWriter(fileStream);
                }
                else
                {
                    fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write);
                    writer     = new StreamWriter(fileStream);
                }
                writer.WriteLine(orderid);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }
Exemplo n.º 18
0
        private void LoadMatches()
        {
            FileInfo summaryFile = new FileInfo(App.SummaryPath);
              var dir = new DirectoryInfo(App.Rootpath);
              if (!dir.Exists) dir.Create();

              Logger.WriteLine("Loading replays from {0}", App.Rootpath);

              FileStream loadSummary;
              if (!summaryFile.Exists) loadSummary = summaryFile.Create();
              else loadSummary = summaryFile.Open(FileMode.Open);
              var mems = new MemoryStream();
              loadSummary.CopyTo(mems);
              loadSummary.Close();

              dynamic summary;
              try {
            summary = MFroehlich.Parsing.MFro.MFroFormat.Deserialize(mems.ToArray());
            Logger.WriteLine("Loaded {0} summaries from {1}", summary.Count, summaryFile.FullName);
              } catch (Exception x) {
            summary = new JSONObject();
            Logger.WriteLine(Priority.Error, "Error loading summaries {0}, starting new summary list", x.Message);
              }
              dynamic newSummary = new JSONObject();

              List<FileInfo> files = new DirectoryInfo(App.Rootpath).EnumerateFiles("*.lol").ToList();
              files.Sort((a, b) => b.Name.CompareTo(a.Name));

              int summaries = 0;
              var timer = new System.Diagnostics.Stopwatch(); timer.Start();

              for (int i = 0; i < files.Count; i++) {
            string filename = files[i].Name.Substring(0, files[i].Name.Length - 4);

            ReplayItem item;
            if (summary.ContainsKey(filename)) {
              item = new ReplayItem((SummaryData) summary[filename], files[i]);
              newSummary.Add(filename, summary[filename]);
            } else {
              SummaryData data = new SummaryData(new MFroReplay(files[i]));
              newSummary.Add(filename, JSONObject.From(data));
              item = new ReplayItem(data, files[i]);
              summaries++;
            }
            item.MouseUp += OpenDetails;
            replays.Add(item);
              }

              Logger.WriteLine("All replays loaded, took {0}ms", timer.ElapsedMilliseconds);

              using (FileStream saveSummary = summaryFile.Open(FileMode.Open)) {
            byte[] summBytes = MFroehlich.Parsing.MFro.MFroFormat.Serialize(newSummary);
            saveSummary.Write(summBytes, 0, summBytes.Length);
            Logger.WriteLine("Saved summaries, {0} total summaries, {1} newly generated", newSummary.Count, summaries);
              }
              Search();
              ReplayArea.Visibility = System.Windows.Visibility.Visible;
              LoadArea.Visibility = System.Windows.Visibility.Hidden;
              Console.WriteLine("DONE");
        }
        public async Task Reduce(FileInfo input, FileInfo output)
        {
            if (input == null)
            {
                throw new ArgumentException("Missing parameter input", "input");
            }

            if (output == null)
            {
                throw new ArgumentException("Missing parameter outputDirectory", "outputDirectory");
            }

            var fileName = input.Name;
            var endpoint = new Uri("https://api.accusoft.com/v1/imageReducers/" + fileName);
            
            using (var client = new WebClient())
            {
                client.Headers.Add("acs-api-key", _apiKey);
                client.Headers.Add("Content-Type", input.Extension == "png" ? "image/png" : "image/jpg");

                using (var reader = new BinaryReader(input.OpenRead()))
                {
                    var data = reader.ReadBytes((int)reader.BaseStream.Length);
                    var result = await client.UploadDataTaskAsync(endpoint, "POST", data);

                    using (var writeStream = output.Create())
                    {
                        await writeStream.WriteAsync(result, 0, result.Length);
                    }
                }
            }
        }
Exemplo n.º 20
0
 /// <summary>
 /// Log日志写入本地文件
 /// </summary>
 /// <param name="info"></param>
 public void LogWrite(string Remarks, string info)
 {
     try
     {
         System.IO.FileInfo fileInfo = new System.IO.FileInfo(_FilePath);
         if (!fileInfo.Exists)
         {
             fileStream = fileInfo.Create();
             writer     = new StreamWriter(fileStream);
         }
         else
         {
             fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
             writer     = new StreamWriter(fileStream);
         }
         writer.WriteLine(DateTime.Now + "--类型:" + Remarks + "---->" + "\r\n描述:" + info);
     }
     finally
     {
         if (writer != null)
         {
             writer.Close();
             writer.Dispose();
             fileStream.Close();
             fileStream.Dispose();
         }
     }
 }
Exemplo n.º 21
0
        private static bool VerificaRelatorio(string Nome_Relatorio)
        {
            Nome_Relatorio = Nome_Relatorio.RemoverCaracteres().Replace(" ", "_");
            string vFilePath       = "";
            string vURL_Relatorios = "";

            if ((Utils.Parametros.pubTerminal == null ? "" : Utils.Parametros.pubTerminal) != "")
            {
                vFilePath       = TCN_CadParamGer.BuscaVlString("PATH_RELATORIO", Utils.Parametros.pubTerminal, null);
                vURL_Relatorios = TCN_CadParamGer.BuscaVlString("URL_RELATORIOS", Utils.Parametros.pubTerminal, null);
            }
            else
            {
                vFilePath       = Utils.Parametros.pubPathAliance.Trim();
                vURL_Relatorios = Utils.Parametros.pubPathAliance.Trim();
            }

            if (!string.IsNullOrEmpty(vFilePath))
            {
                if (!vFilePath.EndsWith("\\"))
                {
                    vFilePath += "\\";
                }
            }


            if (!File.Exists(vFilePath + Nome_Relatorio + ".rst"))
            {
                //CRIA O MODELO
                if (!(System.IO.File.Exists(vFilePath + "Modelo.rst")) && (vURL_Relatorios != ""))
                {
                    //tentar baixar da internet
                    try
                    {
                        System.Net.WebClient www = new System.Net.WebClient();
                        www.BaseAddress = vURL_Relatorios;
                        byte[] buff = new byte[0];
                        buff = www.DownloadData(vURL_Relatorios + "Modelo.rst");

                        System.IO.FileInfo   fInfo = new System.IO.FileInfo(vFilePath + "Modelo.rst");
                        System.IO.FileStream arq   = fInfo.Create();

                        arq.Write(buff, 0, buff.Length);
                        arq.Close();
                    }
                    catch (System.Net.WebException ex)
                    {
                        throw new Exception("Ocorreu um erro na tentativa de efetuar DOWNLOAD do relatorio de Modelo do Site da Tecnoaliance, Contacte o suporte /n" + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Erro: " + ex.Message.Trim());
                    }
                }

                return(GeraArquivoRelatorio(Nome_Relatorio + ".rst", vFilePath));
            }

            return(false);
        }
Exemplo n.º 22
0
        static void Main()
        {
            // Создаем новый файл в корневом каталоге диска D:
            var file = new FileInfo(@".\Test.txt");

            FileStream stream = file.Create();

            // Выводим основную информацию о созданном файле.
            Console.WriteLine("Full Name   : {0}", file.FullName);
            Console.WriteLine("Attributes  : {0}", file.Attributes.ToString());
            Console.WriteLine("CreationTime: {0}", file.CreationTime);

            Console.WriteLine("Нажмите любую клавишу для удаления файла.");
            Console.ReadKey();

            // Закрываем FileStream.
            stream.Close();

            // Удаляем файл.
            file.Delete();

            Console.WriteLine("Файл успешно удален.");

            // Delay.
            Console.ReadKey();
        }
Exemplo n.º 23
0
 static void Main(string[] args)
 {
     DirectoryInfo dir = new FileInfo(DEST).Directory;
     if (dir != null)
         dir.Create();
     new Sample01_HelloWorld().CreatePdf(DEST);
 }
Exemplo n.º 24
0
 static public bool SaveTextFile(string fullPath_, string text_)
 {
     try
     {
         FileInfo fileInfo = new System.IO.FileInfo(fullPath_);
         if (!fileInfo.Directory.Exists)
         {
             fileInfo.Directory.Create();
         }
         using (FileStream fs = fileInfo.Create())
         {
             using (TextWriter tw = new StreamWriter(fs, System.Text.Encoding.UTF8))
             {
                 tw.Write(text_);
                 tw.Close();
             }
             fs.Close();
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// Cria um arquivo no caminho completo informado com o conteudo informado
        /// </summary>
        /// <param name="filename">Caminho do arquivo a ser criado</param>
        /// <param name="content">Conteúdo do arquivos</param>
        /// <returns>True se consegue criar o arquivo e false caso não consiga</returns>
        public static bool Create(string filename, string content)
        {
            var bcreated = true;

            if (!MZHelperFile.Exists(filename))
            {
                var fi = new System.IO.FileInfo(filename);
                try
                {
                    //Create the file.
                    using (FileStream fs = fi.Create())
                    {
                        Byte[] info =
                            new UTF8Encoding(true).GetBytes(content);

                        //Add some information to the file.
                        fs.Write(info, 0, info.Length);
                        fs.Flush();
                    }
                }
                catch
                {
                    bcreated = false;
                }
            }
            return(bcreated);
        }
Exemplo n.º 26
0
        public static void ExportSubfile([DefaultVar]ppParser parser, string name, string path)
        {
            for (int i = 0; i < parser.Subfiles.Count; i++)
            {
                if (parser.Subfiles[i].Name == name)
                {
                    FileInfo file = new FileInfo(path);
                    DirectoryInfo dir = file.Directory;
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }

                    using (FileStream fs = file.Create())
                    {
                        IWriteFile subfile = parser.Subfiles[i];
                        ppSubfile ppSubfile = subfile as ppSubfile;
                        if (ppSubfile != null)
                        {
                            ppSubfile.SourceStream = ppSubfile.CreateReadStream();
                        }
                        subfile.WriteTo(fs);
                        if (ppSubfile != null)
                        {
                            ppSubfile.SourceStream = null;
                        }
                    }
                    break;
                }
            }
        }
Exemplo n.º 27
0
        private static FileInfo UploadFile(Stream inputStream, string fileName)
        {
            string path = GetPath();
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = "img";
            }

            string uniqFileName = string.Format(
                "{0}-{1:yyyy-MM-dd_hh-mm-ss-tt}{2}",
                Path.GetFileNameWithoutExtension(fileName),
                DateTime.Now,
                Path.GetExtension(fileName));

            FileInfo file = new FileInfo(Path.Combine(path, uniqFileName));
            using (FileStream fileStream = file.Create())
            {
                inputStream.Seek(0, SeekOrigin.Begin);
                inputStream.CopyTo(fileStream);
            }

            return file;
        }
Exemplo n.º 28
0
        public override void Copy(string From, string To)
        {
            //SwitchOrCreateDir(SuperRootFolder);
            DirectoryInfo dir = Directory.CreateDirectory(SuperRootFolder);
            To = From.Substring(Configuration.SourceFolder.Length);
                //Replace(Configuration.SourceFolder, SuperRootFolder);
            var dirs = To.Split('\\');
            To = SuperRootFolder;
            for (int i = 0; i < dirs.Length - 1; i++)
            {
                dir = base.ProtectedSwitchOrCreateDir(dir, dirs[i]);
                To = Path.Combine(To, dirs[i]);
            }
            To = Path.Combine(To, dirs[dirs.Length - 1]);

            FileInfo info = new FileInfo(To);
            if (!info.Exists)
            {
                using (Stream stream = info.Create())
                {
                    stream.WriteByte(0);
                    stream.Flush();
                }
            }
        }
        public override void Handle()
        {
            EnsureOptions();

            bool directoryIsNewlyCreated = false;
            var currentDirectory = GetAndEnsureDirectory(out directoryIsNewlyCreated);

            var names = Options.Name.Split(new string[]{"/","\\"},StringSplitOptions.RemoveEmptyEntries);

            var fileName = names.Last();
            var directories = names.Except(new List<string>{fileName});

            foreach (var name in directories)
            {
                var currentPath = Path.Combine(currentDirectory.FullName, name);

                currentDirectory = new DirectoryInfo(currentPath);

                if (!currentDirectory.Exists)
                    currentDirectory.Create();
            }

            var fileInfo = new FileInfo(Path.Combine(currentDirectory.FullName, fileName + ".shortc"));
            if (fileInfo.Exists)
                throw new InvalidOperationException(string.Format(Resources.Resources.AddItemHandler_NameAllreadyExists, Options.Name));
            using (var writer = new StreamWriter(fileInfo.Create()))
            {
                writer.WriteLine(Options.Text);
            }

            _Console.WriteLine(Resources.Resources.AddItemHandler_ShortcutCreated);
        }
Exemplo n.º 30
0
    public void WriteLog(string sErrMsg)
    {
        try
            {
                string sFileName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog.txt";
                System.IO.FileInfo objFileInfo = new System.IO.FileInfo(sFileName);
                if (!objFileInfo.Exists)
                    objFileInfo.Create();

                if (objFileInfo.Length > 10485760)
                {
                    string str_number = Guid.NewGuid().ToString();
                    string newFile = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog\\" + str_number + "ErrorLog.txt";
                    objFileInfo.CopyTo(newFile);
                    objFileInfo.Delete();
                }

                string sPathName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "//ErrorLog.txt";//ConfigurationSettings.AppSettings["LogFileName"];

                System.IO.FileStream objFileStream = objFileInfo.Open(System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                System.IO.StreamWriter objWriter = new System.IO.StreamWriter(objFileStream);
                objWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                objWriter.WriteLine("Error Occured at " + DateTime.Now.ToLongDateString() + " : " + DateTime.Now.ToLongTimeString());
                objWriter.WriteLine(sErrMsg);
                objWriter.WriteLine("----------------------------------------------------------------------");
                objWriter.Close();
            }
            catch { }
    }
Exemplo n.º 31
0
 public void log(string info, string fileName)
 {
     logFile = fileName;
     CreateDirectory(logFile);
     try
     {
         System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
         if (!fileInfo.Exists)
         {
             fileStream = fileInfo.Create();
             writer     = new StreamWriter(fileStream);
         }
         else
         {
             fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
             writer     = new StreamWriter(fileStream);
         }
         writer.WriteLine(DateTime.Now + ": " + info);
     }
     finally
     {
         if (writer != null)
         {
             writer.Close();
             writer.Dispose();
             fileStream.Close();
             fileStream.Dispose();
         }
     }
 }
        public void RenameFileWithoutExtension()
        {
            // Type
            var workingDirectory = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "System_IO_FileInfo_Rename"));
            workingDirectory.EnsureDirectoryExists();
            workingDirectory.Clear();

            var @this = new FileInfo(Path.Combine(workingDirectory.FullName, "Examples_System_IO_FileInfo_RenameWithoutExtension.txt"));
            var @thisNewFile = new FileInfo(Path.Combine(workingDirectory.FullName, "Examples_System_IO_FileInfo_RenameWithoutExtension2.txt"));
            bool result1 = @thisNewFile.Exists;

            // Intialization
            using (FileStream stream = @this.Create())
            {
            }

            // Examples
            @this.RenameFileWithoutExtension("Examples_System_IO_FileInfo_RenameWithoutExtension2");

            // Unit Test
            @thisNewFile = new FileInfo(Path.Combine(workingDirectory.FullName, "Examples_System_IO_FileInfo_RenameWithoutExtension2.txt"));
            bool result2 = @thisNewFile.Exists;

            Assert.IsFalse(result1);
            Assert.IsTrue(result2);
        }
Exemplo n.º 33
0
        public static FileInfo Download(AbsoluteUri location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }

            FileInfo file = null;

            var request = WebRequest.Create((Uri)location);
            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (null != stream)
                    {
                        using (var reader = new StreamReader(stream))
                        {
#if NET20
                            file = new FileInfo(StringExtensionMethods.FormatWith("{0}.json", AlphaDecimal.Random()));
                            FileInfoExtensionMethods.Create(file, reader.ReadToEnd());
#else
                            file = new FileInfo("{0}.json".FormatWith(AlphaDecimal.Random()));
                            file.Create(reader.ReadToEnd());
#endif
                        }
                    }
                }
            }

            return file;
        }
Exemplo n.º 34
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderid"></param>
        public void SetCurText(string orderid)
        {
            FileStream fileStream = null;
            StreamWriter writer = null;
            try
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(_fileName);
                if (!fileInfo.Exists)
                {
                    fileStream = fileInfo.Create();
                    writer = new StreamWriter(fileStream);
                }
                else
                {
                    fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write);
                    writer = new StreamWriter(fileStream);
                }
                writer.WriteLine(orderid);

            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }
 public FileOutput()
 {
     _file = new FileInfo("outputLog.txt");
     if (!_file.Exists)
         _file.Create();
     //MessageBox.Show("Файл логов подключен");
 }
Exemplo n.º 36
0
        private bool FileCreate(System.IO.FileInfo cFileInfo)
        {
reFileCreate:
            bool bCreateFile = false;

            if (!cFileInfo.Exists)
            {
                try
                {
                    System.IO.FileStream fstr = cFileInfo.Create();
                    fstr.Close();
                }
                catch (System.IO.DirectoryNotFoundException)
                {
                    if (CreatePath(cFileInfo.DirectoryName))
                    {
                        goto reFileCreate;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            return(bCreateFile);
        }
Exemplo n.º 37
0
        /// <summary>
        ///  初始化
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public static void Initialize(string filePath, string fileName)
        {
            try
            {
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                if (fileName.IndexOf("/", StringComparison.Ordinal) != -1)
                {
                    fileName = fileName.Replace("/", "-");
                }
                var logFile = Path.Combine(filePath, fileName);
                if (!File.Exists(logFile))
                {
                    var directoryInfo = new FileInfo(logFile).Directory;
                    if (directoryInfo != null) directoryInfo.Create();
                }

                _mWriter = new StreamWriter(logFile, true);
                if (_mWriter == null)
                {
                    throw new Exception("文件不存在:" + logFile);
                }
                if (_mWriter.BaseStream.Length < size) return;
                Display("文件已经在5M以上,必须删除!:" + logFile);
            }
            catch (Exception e)
            {
                Display("Logger初始化错误: " + e.Message + " " + e.StackTrace + ".");
            }
        }
Exemplo n.º 38
0
 public void ReadStreamMultipleTimes () 
 {
     FileInfo file = null;
     Stream stream = null;
     try 
     {
         file = new FileInfo ("ReadStreamMultipleTimes");
         stream = file.Create ();
         // attempting to read this stream twice is an error...
         InputStreamResource res = new InputStreamResource (stream, "A temporary resource.");
         Stream streamOne = res.InputStream;
         Stream streamTwo = res.InputStream; // should bail here
     } 
     finally 
     {
         try 
         {
             if (stream != null) 
             {
                 stream.Close ();
             }
             if (file != null
                 && file.Exists) 
             {
                 file.Delete ();
             }
         } 
         catch {}
     }
 }
Exemplo n.º 39
0
 public void log(string info, string fullPath)
 {
     try
     {
         System.IO.FileInfo fileInfo = new System.IO.FileInfo(fullPath);
         if (!fileInfo.Exists)
         {
             fileStream = fileInfo.Create();
             writer     = new StreamWriter(fileStream);
         }
         else
         {
             fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
             writer     = new StreamWriter(fileStream);
         }
         writer.WriteLine("Time:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
         writer.WriteLine(info);
         writer.WriteLine("----------------------------------");
     }
     finally
     {
         if (writer != null)
         {
             writer.Close();
             writer.Dispose();
             fileStream.Close();
             fileStream.Dispose();
         }
     }
 }
Exemplo n.º 40
0
        public void Create_PassesContextCorrectly()
        {
            var fixture = DokanOperationsFixture.Instance;

            var path = fixture.FileName.AsRootedPath();
            string value = $"TestValue for test {nameof(Create_PassesContextCorrectly)}";
            var context = new object();
#if LOGONLY
            fixture.SetupAny();
#else
            fixture.ExpectCreateFile(path, ReadWriteAccess, WriteShare, FileMode.Create, FileOptions.None, context: context);
            fixture.ExpectWriteFile(path, Encoding.UTF8.GetBytes(value), value.Length, context: context);

            fixture.PermitProbeFile(path, Encoding.UTF8.GetBytes(value));
#endif

            var sut = new FileInfo(fixture.FileName.AsDriveBasedPath());

            using (var stream = sut.Create())
            {
                stream.Write(Encoding.UTF8.GetBytes(value), 0, value.Length);
            }

#if !LOGONLY
            fixture.VerifyContextWriteInvocations(path, 1);
#endif
        }
Exemplo n.º 41
0
 public void log(string info)
 {
     try
     {
         System.IO.FileInfo fileInfo = new System.IO.FileInfo(this.logFile);
         if (!fileInfo.Exists)
         {
             this.fileStream = fileInfo.Create();
             this.writer     = new StreamWriter(this.fileStream);
         }
         else
         {
             this.fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
             this.writer     = new StreamWriter(this.fileStream);
         }
         this.writer.WriteLine(info);
     }
     finally
     {
         if (this.writer != null)
         {
             this.writer.Close();
             this.writer.Dispose();
             this.fileStream.Close();
             this.fileStream.Dispose();
         }
     }
 }
Exemplo n.º 42
0
 public static void Main(string[] args)
 {
     DirectoryInfo dir = new FileInfo(DEST).Directory;
     if (dir != null)
         dir.Create();
     new TiledImage().CreatePdf(DEST);
 }
Exemplo n.º 43
0
 public static void Main(string[] args)
 {
     DirectoryInfo dir = new FileInfo(DEST).Directory;
     if (dir != null)
         dir.Create();
     new RepeatImage().ManipulatePdf(SRC, DEST);
 }
Exemplo n.º 44
0
        /// <summary>
        /// 将数据写入文件
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="content">文本内容</param>
        private void SaveDataToFile(string fileName, string content)
        {
            try
            {
                string filePath = Path.GetDirectoryName(fileName);
                FileInfo fi = new FileInfo(fileName);
                StreamWriter sw;

                if (!fi.Exists) // 文件不存在
                {
                    if (!Directory.Exists(filePath)) // 目录不存在
                    {
                        Directory.CreateDirectory(filePath); // 先创建目录,再创建文件
                    }

                    FileStream fs = fi.Create();
                    fs.Close();
                    sw = new StreamWriter(fileName, false, Encoding.GetEncoding("gb2312"));
                }
                else // 文件已经存在
                {
                    sw = new StreamWriter(fileName, false, Encoding.GetEncoding("gb2312"));
                }

                sw.Write(content);
                sw.Close();
            }
            catch (IOException ex)
            {
                MessageBox.Show(string.Format("保存文件{0}时产生IO异常:" + ex.Message, fileName), "保存数据文件",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 45
0
        /*public void write(string info)
         * {
         *  try
         *  {
         *      System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
         *      if (!fileInfo.Exists)
         *      {
         *          fileStream = fileInfo.Create();
         *          writer = new StreamWriter(fileStream);
         *      }
         *      else
         *      {
         *          fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
         *          writer = new StreamWriter(fileStream);
         *      }
         *      writer.WriteLine(DateTime.Now + ": " + info);
         *      writer.WriteLine("----------------------------------");
         *  }
         *  finally
         *  {
         *      if (writer != null)
         *      {
         *          writer.Close();
         *          writer.Dispose();
         *          fileStream.Close();
         *          fileStream.Dispose();
         *      }
         *  }
         * }*/

        public static void write(string info, int level_local = 1)
        {
            if (level_local > level)
            {
                return;
            }

            lock (locker)
            {
                try
                {
                    string FileName  = Process.GetCurrentProcess().MainModule.FileName;
                    string FilePath  = System.IO.Path.GetDirectoryName(FileName);
                    string sFilePath = FilePath + "\\log";

                    string        fileName      = sFilePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    DirectoryInfo directoryInfo = Directory.GetParent(fileName);
                    if (!directoryInfo.Exists)
                    {
                        directoryInfo.Create();
                    }

                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
                    if (!fileInfo.Exists)
                    {
                        fileStream = fileInfo.Create();
                        writer     = new StreamWriter(fileStream);
                    }
                    else
                    {
                        fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
                        writer     = new StreamWriter(fileStream);
                    }

                    string strLog = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":  " + info;
                    writer.WriteLine(strLog);

                    if (Event_ShowLog != null)
                    {
                        Event_ShowLog(strLog, null);
                    }

                    //writer.WriteLine("----------------------------------");
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                        writer.Dispose();
                        fileStream.Close();
                        fileStream.Dispose();
                    }
                }
            }
        }
Exemplo n.º 46
0
 public void creatAppConfig()
 {
     init();
     if (!AppConfigfile.Exists)
     {
         AppConfigfile.Create();
     }
 }
Exemplo n.º 47
0
 /// <summary>
 /// 创建文件
 /// </summary>
 /// <param name="path">路径</param>
 public static void FileCreate(string path)
 {
     System.IO.FileInfo createFile = new System.IO.FileInfo(path); //创建文件
     if (!createFile.Exists)
     {
         System.IO.FileStream fs = createFile.Create();
         fs.Close();
     }
 }
Exemplo n.º 48
0
        public static void saveUsers(Dictionary <String, User> users)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();

            FileInfo fi = new System.IO.FileInfo(@"./../../Data/User Data/Users.dat");

            using (var binaryFile = fi.Create())
            {
                binaryFormatter.Serialize(binaryFile, users);
                binaryFile.Flush();
            }
        }
        public static void Main()
        {
            // ...
            string fileName = @"enumtest.txt";

            System.IO.FileInfo enumFile =
                new System.IO.FileInfo(fileName);
            if (!enumFile.Exists)
            {
                enumFile.Create().Dispose();
            }

            try
            {
                System.IO.FileInfo file =
                    new System.IO.FileInfo(fileName);

                file.Attributes = FileAttributes.Hidden |
                                  FileAttributes.ReadOnly;

                Console.WriteLine($"{file.Attributes} = {(int)file.Attributes}");

                // Only the ReadOnly attribute works on Linux/OSX  (The Hidden attribute does not work on LinuxOSX)
                if (!(System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                      System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.OSX)))
                {
                    // Added in C# 4.0/.NET 4.0
                    if (!file.Attributes.HasFlag(FileAttributes.Hidden))
                    {
                        throw new Exception("File is not hidden.");
                    }
                }

                // Use bit operators prior to C# 4.0/.NET 4.0
                if ((file.Attributes & FileAttributes.ReadOnly) !=
                    FileAttributes.ReadOnly)
                {
                    throw new Exception("File is not read-only.");
                }
            }
            finally
            {
                if (enumFile.Exists)
                {
                    enumFile.Attributes = FileAttributes.Normal;
                    enumFile.Delete();
                }
            }
            // ...
        }
Exemplo n.º 50
0
 /// <summary>
 /// 向文本文件的尾部追加内容
 /// </summary>
 /// <param name="filePath">文件的绝对路径</param>
 /// <param name="content">写入的内容</param>
 /// <param name="maxFileSize">文件最多写入的大小(单位:byte)</param>
 public static void AppendText(string filePath, object content, Int32 maxFileSize = default(Int32))
 {
     try
     {
         string folder = AppDomain.CurrentDomain.BaseDirectory + "/log/" + DateTime.Now.ToString("yyyy/MM") + "/";
         System.IO.DirectoryInfo di = new DirectoryInfo(folder);
         if (!di.Exists)
         {
             di.Create();
         }
         filePath = folder + filePath;
         filePath = filePath.Replace(@"//", @"/");
         System.IO.FileInfo FI = new System.IO.FileInfo(filePath);
         if (!FI.Exists)
         {
             FI.Create().Close();
         }
         else if (maxFileSize != default(Int32))
         {
             var filesize = GetFileSize(filePath);
             if (filesize > maxFileSize)
             {
                 DelFile(filePath);
                 FI.Create().Close();
             }
         }
         using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, true))
         {
             sw.WriteLine(content.ToString());
             sw.Close();
             sw.Dispose();
         }
     }
     catch (Exception ee)
     {
     }
 }
Exemplo n.º 51
0
        public async Task <IFileInfo> CreateFileAsync(string name)
        {
            var file = await Task.Run(() =>
            {
                var fullPath = System.IO.Path.Combine(NativeItem.FullName, name);
                var newFile  = new System.IO.FileInfo(fullPath);
                using (var stream = newFile.Create())
                {
                }

                return(newFile);
            });

            return(new FileInfo(file));
        }
Exemplo n.º 52
0
        // Saving Player's data as binary
        public static string SaveData(Player player)
        {
#if UNITY_STANDALONE
            FileStream file = null;

            // Serialize and saving player's data at specific location.
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                file = File.Create(Application.persistentDataPath + SAVE_PATH_PC);
                bf.Serialize(file, player);

                return("Data was saved at" + Application.persistentDataPath + SAVE_PATH_PC);
            }
            // If it throws a catch, can be seen in console.
            catch (Exception e)
            {
                return("Data couldn't be saved!!!!");
            }
            // Closing file, when it is done.
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
            }
#elif UNITY_ANDROID
            var fi = new System.IO.FileInfo(Application.persistentDataPath + SAVE_PATH_ANDROID);

            try
            {
                // Open file stream, serialize the dictionary and write it to the bin file.
                using (var binaryFile = fi.Create())
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(binaryFile, player);
                    binaryFile.Flush();
                }
                Debug.Log("creating bin succesfull");
                return("succesfull!");
            }
            catch (System.Exception e)
            {
                throw e;
            }
#endif
        }
Exemplo n.º 53
0
 /// <summary>
 /// 写文件
 /// </summary>
 /// <param name="strFilePath"></param>
 /// <param name="strValue"></param>
 /// <param name="charset"></param>
 public static void WriteFile(string strFilePath, string strValue, string charset)
 {
     System.IO.FileInfo oFile = new System.IO.FileInfo(strFilePath);
     if (!oFile.Directory.Exists)
     {
         oFile.Directory.Create();
     }
     if (!oFile.Exists)
     {
         oFile.Create().Close();
     }
     System.IO.StreamWriter oWrite = new StreamWriter(strFilePath, false, System.Text.Encoding.GetEncoding(charset));
     oWrite.Write(strValue);
     oWrite.Flush();
     oWrite.Close();
 }
Exemplo n.º 54
0
        private void saveSettings()
        {
            if (settings == null)
            {
                createNewSettings();
            }

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            FileInfo        fi         = new System.IO.FileInfo(@"settings.bin");
            FileStream      binaryFile = fi.Create();

            binaryFormatter.Serialize(binaryFile, settings);
            binaryFile.Flush();

            binaryFile.Close();
        }
Exemplo n.º 55
0
        public void crearArchivo()
        {
            //Formato de Serializacion/Deserializacion
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            sRuta = sDirectorio + "\\" + sEntidad.Replace(" ", "") + ".dat";
            var fi = new System.IO.FileInfo(@sRuta);

            //Crea el archivo
            using (var binaryFile = fi.Create())
            {
                //Serializa el diccionario con el formato binario
                binaryFile.Flush();
                currentDir = 0;
            }
        }
Exemplo n.º 56
0
        private void jp_LEVEL_6_log(string inputString)//Level 6 writes data
        {
            if (!Directory.Exists(jp_LEVEL_6_folderPath))
            {
                Directory.CreateDirectory(jp_LEVEL_6_folderPath);
            }

            try
            {
                lock (jpLocker_LEVEL_6)
                {
                    if (!fileInfo_6.Exists)
                    {
                        jpFileStream_LEVEL_6 = fileInfo_6.Create();
                        jpWriter_LEVEL_6     = new StreamWriter(jpFileStream_LEVEL_6);
                    }
                    else
                    {
                        jpFileStream_LEVEL_6 = fileInfo_6.Open(FileMode.Append, FileAccess.Write);
                        jpWriter_LEVEL_6     = new StreamWriter(jpFileStream_LEVEL_6);
                    }

                    jpWriter_LEVEL_6.WriteLine("\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\r\n" + "--- LEVEL_6 ---" + inputString);

                    jpWriter_LEVEL_6.Close();
                    jpWriter_LEVEL_6.Dispose();
                    jpFileStream_LEVEL_6.Close();
                    jpFileStream_LEVEL_6.Dispose();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("ATSLog.writeLogByPath exception for logging LEVEL_6 " + inputString + " at path: " + jp_LEVEL_6_fileName + "->" + e.Message);

                jpWriter_LEVEL_6.WriteLine("ATSLog.writeLogByPath exception for logging LEVEL_6 " + inputString + " at path: " + jp_LEVEL_6_fileName + "->" + e.Message);
            }
            finally
            {
                if (jpWriter != null)
                {
                }
            }
        }
Exemplo n.º 57
0
        private void SaveToFile(String toFile)
        {
            System.IO.DirectoryInfo di = new System.IO.FileInfo(toFile).Directory;
            if (!di.Exists)
            {
                di.Create();
            }

            XmlWriterSettings settings = new XmlWriterSettings {
                Indent = true, NewLineOnAttributes = true
            };

            using (XmlWriter writer = XmlWriter.Create(toFile, settings))
            {
                XmlSerializer xs = new XmlSerializer(typeof(TVRenameStats));
                xs.Serialize(writer, this);
                writer.Close();
            }
        }
Exemplo n.º 58
0
        public async Task <IActionResult> Edit(int id, Product product, Microsoft.AspNetCore.Http.IFormFile imageFile)
        {
            if (id != product.ID)
            {
                return(NotFound());
            }


            string newFile = System.IO.Path.Combine(_env.WebRootPath,
                                                    "images", imageFile.FileName);

            System.IO.FileInfo newFileInfo = new System.IO.FileInfo(newFile);
            using (System.IO.FileStream fs = newFileInfo.Create())
            {
                imageFile.CopyTo(fs);
                fs.Close();
            }

            product.Image = "/images/" + imageFile.FileName;

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(product);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductExists(product.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(product));
        }
Exemplo n.º 59
0
 /// <summary>
 /// 向文本文件的尾部追加内容
 /// </summary>
 /// <param name="filePath">文件的绝对路径</param>
 /// <param name="content">写入的内容</param>
 public static void SaveText(string filePath, object content, bool append = false)
 {
     try
     {
         System.IO.FileInfo FI = new System.IO.FileInfo(filePath);
         if (!FI.Exists)
         {
             FI.Create().Close();
         }
         using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, append))
         {
             sw.WriteLine(content.ToString());
             sw.Close();
             sw.Dispose();
         }
     }
     catch (Exception ee)
     {
     }
 }
Exemplo n.º 60
0
        private static bool CanWriteToDirectory(string directory, out Exception exception)
        {
            exception = null;
            try
            {
                string testFileName = Path.Combine(directory, new Guid() + ".testfile");
                var    testFileInfo = new FileInfo(testFileName);
                using (FileStream fileStream = testFileInfo.Create())
                {
                    fileStream.WriteByte(0);
                }
                testFileInfo.Delete();
            }
            catch (Exception e)
            {
                exception = e;
                return(false);
            }

            return(true);
        }