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


C# FileInfo.CreateText方法代码示例

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


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

示例1: _Main

        public static void _Main(string[] args)
        {
            Trace.WriteLine("start");

              var logname = string.Format("{0}_{1}.{2}", "unhand", DateTime.Now.ToString("MMMdd-hhmmss-fffffff"), "log");
              var listenerFile = new System.IO.FileInfo(logname);
              listenerWriter = listenerFile.CreateText();
              listener = new TextWriterTraceListener(listenerWriter);
              Trace.Listeners.Add(listener);
              //Trace.Listeners.Add(new TextWriterTraceListener(Console.Error));
              Trace.AutoFlush = true;

              AppDomain currentDomain = AppDomain.CurrentDomain;
              currentDomain.UnhandledException += new UnhandledExceptionEventHandler(unhand_Handler);

              try
              {
            Trace.WriteLine("throw 1");
            throw new Exception("1");
              }
              catch (Exception e)
              {
            Trace.WriteLine($"Catch clause caught : {e.Message} \n");
              }
              Trace.WriteLine("throw 2");
              throw new Exception("2");
              //Trace.WriteLine("end");
        }
开发者ID:MarcoDorantes,项目名称:spike,代码行数:28,代码来源:unhandled_exceptions.cs

示例2: LogSingleEvent

        public static void LogSingleEvent(string logIndicationText)
        {
            StreamWriter strm;
            string logFileName;
            string workdir = ConfigurationManager.AppSettings["DirectorioTrabajo"];

            logFileName = String.Concat(workdir,
                ConfigurationManager.AppSettings["LogFileNameFormat"]);

            FileInfo archivo = new FileInfo(logFileName);
            DateTime yesterday = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0));

            if (archivo.Exists)
            {
                if (String.Compare(archivo.LastWriteTime.ToString("yyyyMMdd"), yesterday.ToString("yyyyMMdd")) < 0)
                {
                    archivo.Delete();
                    strm = archivo.CreateText();
                }
                else
                {
                    strm = archivo.AppendText();
                }
            }
            else
                strm = archivo.CreateText();

            strm.WriteLine(String.Format("{0} - {1}",
                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), logIndicationText));

            strm.Close();
        }
开发者ID:quiquesys,项目名称:PFACW0001,代码行数:32,代码来源:BitWriter.cs

示例3: BitWriter

        /// <summary>
        /// Inicializa el archivo tambien para su escritura
        /// </summary>
        public BitWriter(string workdir)
        {
            string logFileName;

            logFileName = String.Concat(workdir,
                ConfigurationManager.AppSettings["LogFileNameFormat"]);

            FileInfo archivo = new FileInfo(logFileName);
            DateTime yesterday = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0));

            if (archivo.Exists)
            {
                if (String.Compare(archivo.LastWriteTime.ToString("yyyyMMdd"), yesterday.ToString("yyyyMMdd")) < 0)
                {
                    archivo.Delete();
                    logStream = archivo.CreateText();
                }
                else
                {
                    logStream = archivo.AppendText();
                }
            }
            else
                logStream = archivo.CreateText();

            logStream.WriteLine(String.Format("--- Inicio de control {0} ---",
                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")));
        }
开发者ID:quiquesys,项目名称:PFACW0001,代码行数:31,代码来源:BitWriter.cs

示例4: CurrentDomain_UnhandledException

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            FileInfo logFile = new FileInfo(Environment.CurrentDirectory + @"\error.log");
            if (logFile.Exists)
            {
                logFile.CopyTo(Environment.CurrentDirectory + @"\error.log.bak", true);
            }
            var writer = logFile.CreateText();

            StringBuilder message = new StringBuilder();
            message.AppendLine("----------------------");
            message.AppendLine(DateTime.Now.ToString());
            message.AppendLine();
            if (e.ExceptionObject != null && e.ExceptionObject is Exception)
            {
                var ex = e.ExceptionObject as Exception;
                message.AppendLine(ex.Message);
                if (ex.InnerException != null)
                {
                    message.AppendLine(ex.InnerException.Message);
                    if (ex.InnerException.InnerException != null)
                    {
                        message.AppendLine(ex.InnerException.InnerException.Message);
                        if (ex.InnerException.InnerException.InnerException != null)
                        {
                            message.AppendLine(ex.InnerException.InnerException.InnerException.Message);
                        }
                    }
                }
            }
            message.AppendLine("----------------------");
            writer.Write(message.ToString());
            writer.Close();
        }
开发者ID:BaiMangal,项目名称:nxtManager,代码行数:34,代码来源:App.xaml.cs

示例5: LocalFileIsCreatedInIgnoredFolder

        public void LocalFileIsCreatedInIgnoredFolder([Values(true, false)]bool contentChanges) {
            this.session.EnsureSelectiveIgnoreSupportIsAvailable();
            this.ContentChangesActive = contentChanges;
            var folder = this.remoteRootDir.CreateFolder("ignored");

            this.InitializeAndRunRepo();

            folder.Refresh();
            folder.IgnoreAllChildren();

            this.WaitForRemoteChanges();
            this.AddStartNextSyncEvent();
            this.repo.Run();

            var localFolder = this.localRootDir.GetDirectories()[0].FullName;
            var fileInfo = new FileInfo(Path.Combine(localFolder, "file.txt"));
            using (StreamWriter sw = fileInfo.CreateText()) {
                sw.WriteLine("content");
            }

            this.WaitUntilQueueIsNotEmpty();
            this.AddStartNextSyncEvent();
            this.repo.Run();

            folder.Refresh();
            Assert.Throws<CmisObjectNotFoundException>(() => this.session.GetObjectByPath(folder.Path + "/file.txt"), "The file shouldn't exist on the server, but it does");
        }
开发者ID:OpenDataSpace,项目名称:CmisSync,代码行数:27,代码来源:FileCrud.cs

示例6: Save

 public static void Save(int longestValue)
 {
     FileInfo output = new FileInfo("output.txt");
        StreamWriter writer = output.CreateText();
        writer.Write(longestValue);
        writer.Close();
 }
开发者ID:dmytroproh,项目名称:Algorithms,代码行数:7,代码来源:FileGenerator.cs

示例7: EnsureCpsProjFile

        private void EnsureCpsProjFile(string cpsProjFileName) {
            var fileInfo = new FileInfo(cpsProjFileName);
            if (fileInfo.Exists) {
                return;
            }

            var inMemoryTargetsFile = FileSystemMirroringProjectUtilities.GetInMemoryTargetsFileName(cpsProjFileName);

            var xProjDocument = new XProjDocument(
                new XProject(Toolset.Version, "Build",
                    new XPropertyGroup("Globals", null,
                        new XProperty("ProjectGuid", Guid.NewGuid().ToString("D"))
                    ),
                    new XPropertyGroup(
                        new XDefaultValueProperty("VisualStudioVersion", Toolset.Version),
                        new XDefaultValueProperty("Configuration", "Debug"),
                        new XDefaultValueProperty("Platform", "AnyCPU")
                    ),
                    CreateProjectSpecificPropertyGroup(cpsProjFileName),
                    CreateProjectUiSubcaption(),
                    new XProjElement("ProjectExtensions",
                        new XProjElement("VisualStudio",
                            new XProjElement("UserProperties")
                        )
                    ),
                    new XProjElement("Target", new XAttribute("Name", "Build")),
                    _msBuildImports.SelectMany(CreateMsBuildExtensionXImports),
                    new XImportExisting(inMemoryTargetsFile)
                )
            );

            using (var writer = fileInfo.CreateText()) {
                xProjDocument.Save(writer);
            }
        }
开发者ID:Microsoft,项目名称:RTVS,代码行数:35,代码来源:FileSystemMirroringProjectFileGenerator.cs

示例8: GetAngularFreelancers

        public async Task GetAngularFreelancers()
        {
            int? postId = GetPostId();
            if (!postId.HasValue)
                return;
             
            string endpoint = string.Format(apiUrl, postId);
            var webClient = new WebClient();
            string content = webClient.DownloadString(endpoint);
            var comments = ((JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content))["kids"];
            var title = ((JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content))["title"];

            var fileName = GenerateDestFileName(title);
            destFile = new FileInfo(fileName);
            if (!destFile.Exists)
            {
                var sw = destFile.CreateText();
                sw.Close();

            }

            int i = 1;
            foreach (var item in comments)
            {
                // await WriteTextAsync(destFile.FullName, ",\r\n");
                Console.WriteLine("Get freelancer number {0}", i);
                await ExtractAndSaveFreelancer(item, destFile, i);
                i++;
            }
        }
开发者ID:flyeven,项目名称:AngJobs,代码行数:30,代码来源:HackerNews.cs

示例9: Button_Click_2

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (!File.Exists(CobieFile.Text))
                return;


            var filters = new List<string>();
            filters.Add("text file|*.txt");
            //filters.Add(@"Automation format|*.json");
            //filters.Add(@"Automation format|*.xml");

            var file = GetSaveFileName("Select destination file", filters);
            if (file == "")
                return;
            
            string read;
            _f = Facility.ReadCobie(CobieFile.Text, out read);
            var flogger = new FileInfo(file);
            using (var logger = flogger.CreateText())
            {
                _f.ValidateUK2012(logger, true);
            }
            if (flogger.Exists)
            {
                Process.Start(flogger.FullName);
                ImproveCObie.IsEnabled = true;
            }
        }
开发者ID:tnesser,项目名称:XbimWindowsUI,代码行数:28,代码来源:MainWindow.xaml.cs

示例10: WriteFile

        public static bool WriteFile(string data, FileInfo fileInfo)
        {
            bool success = false;
            try
            {
                if (fileInfo == null || fileInfo.Directory==null) return false;
                                                  
                if (!fileInfo.Directory.Exists)
                {
                    Directory.CreateDirectory(fileInfo.Directory.ToString());
                }
                                    
                using (var streamWriter = fileInfo.CreateText() )
                {
                    streamWriter.Write(data, EncodingWrite);
                    success = true;
                }
            }
            catch (Exception ex)
            {
                WL(ExceptionUtil.GetException(ex));
                WL("\nPress a key ... ");
                Console.ReadKey();
            }

            return success;
        }
开发者ID:trevorjobling,项目名称:Google-Maps-Clustering-CSharp,代码行数:27,代码来源:FileUtil.cs

示例11: Main

        static void Main()
        {
            // Создаем файл.
            var file = new FileInfo("Text.txt");

            // С помощью экземпляра StreamWriter записываем в файл несколько строк текста.
            StreamWriter writer = file.CreateText();

            writer.WriteLine("Первая строка текста...");
            writer.WriteLine("Вторая строка текста...");

            // Вставляем символ начала новой строки.
            writer.Write(writer.NewLine);

            writer.WriteLine("Третья строка чисел:");

            for (int i = 0; i < 10; i++)
            {
                writer.Write(i + " ");
            }

            // Вставляем символ начала новой строки.
            writer.Write(writer.NewLine);

            // Метод Close() автоматически очищает все буферы!
            writer.Close();

            Console.WriteLine("Файл Text.txt создан и в него записан текст.");

            // Delay.
            Console.ReadKey();
        }
开发者ID:vbre,项目名称:CS_2015_Winter,代码行数:32,代码来源:Program.cs

示例12: FileTelemetryConsumer

 public FileTelemetryConsumer(FileInfo file)
 {
     _logFileName = file.FullName;
     var fileExists = File.Exists(_logFileName);
     _logOutput = fileExists ? file.AppendText() : file.CreateText();
     file.Refresh();
 }
开发者ID:PaulNorth,项目名称:orleans,代码行数:7,代码来源:FileTelemetryConsumer.cs

示例13: btn_filedb_Click

 private void btn_filedb_Click(object sender, RoutedEventArgs e)
 {
     string path = System.Environment.CurrentDirectory + "\\filepath.txt";
     string filepath_db = System.Environment.CurrentDirectory + "\\bd4.mdf";
     FileInfo fi1;
     if (System.IO.File.Exists(path))//проверка на существование файла настроек
     {
         fi1 = new FileInfo(path);
         using (StreamReader sr = fi1.OpenText())
         {
             string s = sr.ReadLine();
             if (System.IO.File.Exists(s))//проверка на путь в нем
             {
                 filepath_db = s;
             }
         }
     }
     if (!System.IO.File.Exists(filepath_db))
     {
         filepath_db = @"C:\";
     }
     System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
     dialog.InitialDirectory = filepath_db;
     dialog.Filter = "DB File |*.mdf";
     if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         filepath_db = dialog.FileName;
     }
     else filepath_db = System.Environment.CurrentDirectory + "\\bd4.mdf";
     fi1 = new FileInfo(path);
     using (StreamWriter sr = fi1.CreateText())
     {
         sr.WriteLine(filepath_db);
     }
 }
开发者ID:Kirk7by,项目名称:mandarin,代码行数:35,代码来源:MandarinForm.xaml.cs

示例14: CreateTestFileAndCopyToFolder

        public FileInfo CreateTestFileAndCopyToFolder(string pathToCopyTo)
        {
            string path = Path.GetTempFileName();
            FileInfo fi1 = new FileInfo(path);

            //Create a file to write to.
            using (StreamWriter sw = fi1.CreateText())
            {
                sw.WriteLine("Title");
                sw.WriteLine("Lots of happenings");
                sw.WriteLine("Bazinga");
            }

            try
            {
                //Copy the file.
                fi1.CopyTo(pathToCopyTo+"\\TempFile.txt");
                FileInfo fi2 = new FileInfo(pathToCopyTo + "\\TempFile.txt");

                return fi2;
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
            return null;
        }
开发者ID:x2find,项目名称:FileShare2Find,代码行数:27,代码来源:TestSupport.cs

示例15: OutputLogToFile

        private static void OutputLogToFile(int type, string tag, string message)
        {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
            switch (type)
            {
                case LOG_TYPE_INFO:
                    tag = "I: " + tag;
                    break;
                case LOG_TYPE_WARNING:
                    tag = "W: " + tag;
                    break;
                case LOG_TYPE_ERROR:
                    tag = "E: " + tag;
                    break;
            }
            StreamWriter sw;
            FileInfo t = new FileInfo(Application.dataPath + "//Log.txt");
            if (!t.Exists)
            {
                sw = t.CreateText();
            }
            else
            {
                sw = t.AppendText();
            }
            sw.WriteLine(tag + message);
            sw.Close();
            sw.Dispose();
#endif
        }
开发者ID:xinfushe,项目名称:AndroidUtils-for-Unity3D,代码行数:30,代码来源:LogUtils.cs


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