当前位置: 首页>>代码示例>>C#>>正文


C# FileInfo.Create方法代码示例

本文整理汇总了C#中System.IO.FileInfo.Create方法的典型用法代码示例。如果您正苦于以下问题:C# FileInfo.Create方法的具体用法?C# FileInfo.Create怎么用?C# FileInfo.Create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.FileInfo的用法示例。


在下文中一共展示了FileInfo.Create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: test000_FirstPack

        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();
            }
        }
开发者ID:gilran,项目名称:GitSharp,代码行数:32,代码来源:IndexPackTests.cs

示例2: CreateGUID

        /// <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;
        }
开发者ID:sr3dna,项目名称:big5sync,代码行数:37,代码来源:ProfilingGUIDHelper.cs

示例3: CreateDefaultProfile

        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;
        }
开发者ID:sr3dna,项目名称:big5sync,代码行数:35,代码来源:ProfilingXMLHelper.cs

示例4: CreateZipFile

        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);
        }
开发者ID:ChuangYang,项目名称:Z.ExtensionMethods,代码行数:32,代码来源:FileInfo.CreateZipFile.cs

示例5: DownloadInParallel

        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);
                    }
                });
        }
开发者ID:AndreasPresthammer,项目名称:HanselDownloader,代码行数:28,代码来源:Program.cs

示例6: Initialize

        /// <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 + ".");
            }
        }
开发者ID:yaozd,项目名称:DapperTemplateMultiDatabase,代码行数:37,代码来源:Logger.cs

示例7: Download

        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;
        }
开发者ID:KarlDirck,项目名称:cavity,代码行数:32,代码来源:JsonUriAttribute.cs

示例8: Handle

        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);
        }
开发者ID:jeppevammenkristensen,项目名称:Shortcuts,代码行数:32,代码来源:AddItemHandler.cs

示例9: SaveDataToFile

        /// <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);
            }
        }
开发者ID:viticm,项目名称:pap2,代码行数:38,代码来源:MainForm.cs

示例10: UploadFile

        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;
        }
开发者ID:felix1313,项目名称:Shop,代码行数:28,代码来源:ManageItemsController.cs

示例11: LoadMatches

        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");
        }
开发者ID:mfro,项目名称:LeagueReplay,代码行数:60,代码来源:MainWindow.xaml.cs

示例12: ExceptionLogger

 /// <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;
     }
 }
开发者ID:jimva3hj,项目名称:hamqsler,代码行数:39,代码来源:ExceptionLogger.cs

示例13: button2_Click

        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");
        }
开发者ID:rsdgjb,项目名称:IntegrationValidationApp,代码行数:26,代码来源:MainWindow.xaml.cs

示例14: Save

        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();
                    }
                }
            }
        }
开发者ID:Mahdi-K,项目名称:Licensing,代码行数:25,代码来源:ProjectService.cs

示例15: CreateDatabase

        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();
                }
            }
        }
开发者ID:rho24,项目名称:PocoDb,代码行数:26,代码来源:CompactDbHelper.cs


注:本文中的System.IO.FileInfo.Create方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。