CreateText() public method

public CreateText ( ) : StreamWriter
return StreamWriter
        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");
        }
Example #2
0
        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();
        }
Example #3
0
        /// <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")));
        }
Example #4
0
        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();
        }
Example #5
0
        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");
        }
Example #6
0
 public static void Save(int longestValue)
 {
     FileInfo output = new FileInfo("output.txt");
        StreamWriter writer = output.CreateText();
        writer.Write(longestValue);
        writer.Close();
 }
        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);
            }
        }
Example #8
0
        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;
            }
        }
Example #9
0
 public bool SaveData(MPcs mPcs)
 {
     string path = TbLocal.Text.Trim();
     if (string.IsNullOrEmpty(path))
     {
         MessageBox.Show("请输入或选择本地存储路径!");
         TbLocal.Focus();
         return false;
     }
     if (!Directory.Exists(path))
     {
         MessageBox.Show("您选择的目录不存在!");
         return false;
     }
     try
     {
         string file = Path.Combine(path, "amon.sync");
         FileInfo info = new FileInfo(file);
         if (!info.Exists)
         {
             StreamWriter writer = info.CreateText();
             writer.Write("Demo");
             writer.Close();
         }
         mPcs.LocalRoot = path;
         return true;
     }
     catch (Exception exp)
     {
         MessageBox.Show(exp.Message);
         TbLocal.Focus();
         return false;
     }
 }
Example #10
0
 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);
     }
 }
Example #11
0
        static void writeToFile(string text)
        {
            FileInfo logFile;
            int day, month, year;
            day = DateTime.Now.Day;
            month = DateTime.Now.Month;
            year = DateTime.Now.Year;

            string fileName = "Logger_" + day + "_" + month + "_" + year;
            logFile = new FileInfo(HostingEnvironment.ApplicationPhysicalPath + @".\Logs\" + fileName);
            if (!logFile.Exists)
            {
                using(StreamWriter sw = logFile.CreateText())
                {
                    sw.WriteLine(DateTime.Now + " : " + text);
                }
            }
            else
            {
                using(StreamWriter sw = logFile.AppendText())
                {
                    sw.WriteLine(DateTime.Now + " : " + text);
                }
            }
        }
Example #12
0
        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();
        }
 public FileTelemetryConsumer(FileInfo file)
 {
     _logFileName = file.FullName;
     var fileExists = File.Exists(_logFileName);
     _logOutput = fileExists ? file.AppendText() : file.CreateText();
     file.Refresh();
 }
Example #14
0
        public static bool Save(String filePath, Profile profile)
        {
            StreamWriter writer;
            FileInfo info=new FileInfo(filePath);

            try
            {
                if (info.Exists)
                    writer = new StreamWriter(filePath);
                else
                    writer = info.CreateText();

                writer.AutoFlush = false;

                writer.WriteLine(profile.Name);
                writer.WriteLine(profile.InstructionsCount);

                for (int i = 0; i < profile.InstructionsCount; ++i)
                    writer.WriteLine(profile[i].phrase + FILE_DATASEPARATOR + (int)profile[i].commandType + FILE_DATASEPARATOR + profile[i].axis + FILE_DATASEPARATOR + profile[i].value + FILE_DATASEPARATOR + profile[i].control + FILE_DATASEPARATOR + profile[i].shift);

                writer.Flush();
                writer.Close();
            }
            catch (Exception) { return false; }

            return true;
        }
        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;
        }
        public static void WriteFile(string data, FileInfo fileInfo)
        {
            if (fileInfo.With(f => f.Directory) == null) throw new ArgumentException("fileInfo");
            if (!fileInfo.Directory.Exists) Directory.CreateDirectory(fileInfo.Directory.ToString());

            using (var streamWriter = fileInfo.CreateText()) streamWriter.Write(data, EncodingWrite);
        }
Example #17
0
 public bool writeProfile(string path, Profiles pro)
 {
     doc = new FileInfo(path);
     try
     {
         //If there is no current file, then create a new one
         if (!File.Exists(path))
         {
             StreamWriter stream = doc.CreateText();
             LitJson.JsonWriter writer = new LitJson.JsonWriter(stream);
             LitJson.JsonMapper.ToJson(pro, writer);
             stream.Close();
             return true;
         }
         else //If there is already a file
         {
             StreamWriter stream = new StreamWriter(doc.FullName);
             LitJson.JsonWriter writer = new LitJson.JsonWriter(stream);
             LitJson.JsonMapper.ToJson(pro, writer);
             stream.Close();
             return true;
         }
     }
     catch (Exception ex)
     {
         MeCore.Dispatcher.Invoke(new System.Windows.Forms.MethodInvoker(delegate
         {
             new ErrorReport(ex).Show();
         }));
         return false;
     }
 }
        static void runFileInfo()
        {
            string path = Path.GetTempFileName();
            FileInfo fi = new FileInfo(path);

            if (!fi.Exists)
            {
                // create a file to write to.
                using (StreamWriter writer = fi.CreateText())
                {
                    writer.WriteLine("Hello");
                    writer.WriteLine("And");
                    writer.WriteLine("Welcome");
                }
            }

            // open the file to read from.
            using (StreamReader reader = fi.OpenText())
            {
                string s = "";
                while ((s = reader.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }
Example #19
0
 public static void WriteTxt(String contents, String fileName)
 {
     FileInfo t = new FileInfo(fileName);
     StreamWriter Tex = t.CreateText();
     Tex.Write(contents);
     Tex.Close();
 }
 private void DeployCurlFile(sFreeSwitchModuleFile file)
 {
     string confSection = file.ConfigurationSectionString;
     string ip = (string)Settings.Current[Constants.SERVER_IP_SETTING_NAME];
     int port = (int)Settings.Current[Constants.SERVER_PORT_SETTING_NAME];
     ip = (ip == null ? "127.0.0.1" : (ip == "0.0.0.0" ? "127.0.0.1" : ip));
     confSection = confSection.Replace("<bindings>", "<bindings>" + String.Format(CONFIGURATION_BINDING_TEMPLATE, new object[]{
         "configuration",
         ip,
         port,
         EmbeddedHandlerFactory.BASE_PATH+ConfigurationWebHandler.BASE_PATH+ConfigurationWebHandler.CONFIGURATION_PATH
     }) + String.Format(CONFIGURATION_BINDING_TEMPLATE, new object[]{
         "directory",
         ip,
         port,
         EmbeddedHandlerFactory.BASE_PATH+ConfigurationWebHandler.BASE_PATH+ConfigurationWebHandler.DIRECTORY_PATH
     }) + String.Format(CONFIGURATION_BINDING_TEMPLATE, new object[]{
         "dialplan",
         ip,
         port,
         EmbeddedHandlerFactory.BASE_PATH+ConfigurationWebHandler.BASE_PATH+ConfigurationWebHandler.DIALPLAN_PATH
     }));
     DirectoryInfo di = new DirectoryInfo(Settings.Current[Constants.BASE_PATH_NAME].ToString() + Path.DirectorySeparatorChar + Constants.DEFAULT_CONF_DIR + Path.DirectorySeparatorChar + Constants.DEFAULT_AUTOLOAD_CONF_DIR);
     if (!di.Exists)
         di.Create();
     FileInfo fi = new FileInfo(di.FullName + Path.DirectorySeparatorChar + file.Name + ".xml");
     StreamWriter sw = fi.CreateText();
     sw.Write(confSection);
     sw.Flush();
     sw.Close();
 }
Example #21
0
        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++;
            }
        }
Example #22
0
		public string WriteLog(string s)
		{
			try
			{
				FileInfo fi = new FileInfo("J:\\_net\\sys.log");
				StreamWriter sw;
				if (fi.Exists)
					sw = fi.AppendText();
				else
					sw = fi.CreateText();
				sw.WriteLine(s + "\r\n");
				sw.Close();
			}
			catch (IOException ex)
			{
				return "IO Error";
			}
			catch (UnauthorizedAccessException ex)
			{
				return "Unauthorized Access";
			}
			catch (SecurityException ex)
			{
				return "Security Error";
			}
			catch (NotSupportedException ex)
			{
				return "not supported";
			}
			return "Hello World";
		}
        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
        }
Example #24
0
        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;
        }
        public List<String> Categories()
        {
            List<String> categories = (new String[] { "System", "Processor", "Memory", "Process", "Paging File", "PhysicalDisk", "Server", "IP", "UDP", "TCP", "Network Interface", "Cache" }).ToList();

            String configName = Assembly.GetExecutingAssembly().Location;
            FileInfo fi = new FileInfo(configName);
            fi = new FileInfo(fi.DirectoryName + "\\categories.txt");
            if (!fi.Exists)
                using (var fw = fi.CreateText())
                {
                    foreach (String row in categories)
                        fw.WriteLine(row);
                }
            else
            {
                using (var fr = fi.OpenText())
                {
                    List<String> s = new List<String>();
                    String line;
                    while ((line = fr.ReadLine()) != null)
                        s.Add(line);
                    categories = s;

                }
            }
            return categories;
        }
Example #26
0
 private void WriteFile(FileInfo file)
 {
     using(TextWriter writer = file.CreateText())
     {
         var s = new XmlSerializer(typeof (ConfigurationMemento));
         s.Serialize(writer,_memento);
     }
 }
Example #27
0
        public static void SaveText(string text, string filePath)
        {
            var fileInfo = new FileInfo(filePath);

            TextWriter writer = fileInfo.CreateText();
            writer.Write(text);
            writer.Close();
        }
        private void writeFile(string text, string path)
        {
            var fileInfo = new FileInfo(path);
            StreamWriter writer = fileInfo.CreateText();
            writer.Write(text);

            writer.Close();
        }
Example #29
0
        public static void createCharacter()
        {
            int numberInParty;
            Console.WriteLine("How many characters do you want in your party ?");
            numberInParty = Convert.ToInt32(Console.ReadLine());
            FileInfo characterSpread = new FileInfo("Characters.txt");
            StreamWriter text = characterSpread.CreateText();
            int[,] basicStats = new int[5, numberInParty];
            string[] nameOutput = new string[numberInParty];
            for (int i = 0; i < numberInParty; i++)
            {
                Console.WriteLine("Please enter next character's name: ");
                string nameInput = (Console.ReadLine());
                string[] errorCheck = { "Character", "Dexterity", "Strength", "Constitution"};
                if (Array.IndexOf(errorCheck,nameInput) != -1)
                {
                    Console.WriteLine("Dumbass, quit trying to break my stupid program!");
                    Console.WriteLine("Next time try a different character name.");
                    System.Threading.Thread.Sleep(3000);
                    System.Environment.Exit(0);
                }
                nameOutput[i] = nameInput;
                Console.WriteLine("Now to roll for Attributes");
                for (int reroll = 1; reroll < 5;)
                {
                    int rollForDexterity = RandomNumber.Next(1, 20);
                    int rollForStrength = RandomNumber.Next(1, 20);
                    int rollForConstitution = RandomNumber.Next(1, 20);
                    Console.WriteLine("Dexterity -- Strength -- Constitution");
                    Console.WriteLine("    " + rollForDexterity + "            " + rollForStrength + "         " + rollForConstitution);
                    Console.WriteLine("Do you like this roll ? 'y' to keep it or 'n' to roll again. " + (4 - reroll) + " rolls left");
                    string chooseReroll = (Console.ReadLine()).ToLower();

                    if (chooseReroll.StartsWith("y"))
                    {
                        basicStats[0, i] = rollForDexterity;
                        basicStats[1, i] = rollForStrength;
                        basicStats[2, i] = rollForConstitution;
                        text.WriteLine("Character " + (i + 1) + ": " + nameOutput[i] + " -- Dexterity:" + rollForDexterity + " -- Strength:" + rollForStrength + " -- Constitution:" + rollForConstitution);
                        reroll = reroll + 5;
                    }
                    else if (reroll == 4)
                    {
                        Console.WriteLine("Well too bad, this is what you get. Next Character.");
                        basicStats[0, i] = rollForDexterity;
                        basicStats[1, i] = rollForStrength;
                        basicStats[2, i] = rollForConstitution;
                        text.WriteLine("Character " + (i + 1) + ": " + nameOutput[i] + " -- Dexterity:" + rollForDexterity + " -- Strength:" + rollForStrength + " -- Constitution:" + rollForConstitution);
                        reroll++;
                    }
                    else
                    {
                        reroll++;
                    }
                }
            }
            text.Close();
        }
Example #30
0
        static void Main(string[] args)
        {
            Console.WriteLine("reading drives\n");
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                Console.WriteLine("{0} : {1}",drive.Name, drive.DriveType);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("reading directories\n");

            DirectoryInfo dirInfo = new DirectoryInfo(@"C:\");
            foreach (DirectoryInfo item in dirInfo.GetDirectories())
            {
                Console.WriteLine(item.FullName);
            }
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("read files");
            foreach (FileInfo item in dirInfo.GetFiles())
            {
                Console.WriteLine(item.FullName);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("Create directory");
            DirectoryInfo newDir = new DirectoryInfo(@"C:\DeleteMe");
            if (!newDir.Exists)
            {
                newDir.Create();
                Console.WriteLine("Folder created");
            }
            else
                Console.WriteLine("Directory already exists.");

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("creating file");
            FileInfo fInfo = new FileInfo(@"C:\deleteme\mynewfile.txt");
            fInfo.CreateText();

            Console.WriteLine("copy file");
            fInfo.CopyTo(@"c:\deleteme\Mycopiedfile.txt");

            Console.WriteLine("move file");
            FileInfo fInfo2 = new FileInfo(@"C:\deleteme\MycopiedFile.txt");
            fInfo2.MoveTo(@"c:\deleteme\mythirdfile.txt");

            Console.WriteLine("done");
            Console.ReadLine();
        }
 public virtual void SaveToFile(string fileName)
 {
     System.IO.StreamWriter streamWriter = null;
     try
     {
         string             xmlString = Serialize();
         System.IO.FileInfo xmlFile   = new System.IO.FileInfo(fileName);
         streamWriter = xmlFile.CreateText();
         streamWriter.WriteLine(xmlString);
         streamWriter.Close();
     }
     finally
     {
         if ((streamWriter != null))
         {
             streamWriter.Dispose();
         }
     }
 }
Example #32
0
        public void updateAppConfig(string key, string value)
        {
            init();

            if (AppConfigfile.Exists)
            {
                AppConfigfile.Delete();
            }

            sw = AppConfigfile.CreateText();

            sw.WriteLine("<?xml version=\"" + "1.0\"?>");
            sw.WriteLine("<configuration>");
            sw.WriteLine("<connectionStrings>");
            sw.WriteLine("<add name=\"Default\" connectionString=\"Max Pool Size = 512;server=" + "." + ";uid=sa; pwd=esun5005;database=ESUNNET\" providerName=\"System.Data.SqlClient\" />");
            sw.WriteLine("</connectionStrings>");
            sw.WriteLine(" <appSettings>");
            if (key == "LeavePath")
            {
                sw.WriteLine("<add key=\"LeavePath\"  value=\"" + value + "\"/>");
                sw.WriteLine("<add key=\"RecordPath\"  value=\"" + value + "\"/>");
            }
            // sw.WriteLine("<add key=\"LeavePath\"  value=\"" + "D:\\work\\z中百集团\\VXML" + "\"/>");
            if (key == "RecordPath")
            {
                sw.WriteLine("<add key=\"LeavePath\"  value=\"" + value + "\"/>");
                sw.WriteLine("<add key=\"RecordPath\"  value=\"" + value + "\"/>");
            }
            sw.WriteLine("</appSettings>");
            sw.WriteLine("</configuration>");

            sw.AutoFlush = true;
            AppConfigfile.Refresh();
            sw.Flush();
            if (sw != null)
            {
                sw.Close();
            }
            sw.Dispose();
        }
        /// <summary>
        /// Saves the entity.
        /// </summary>
        /// <param name="en">En.</param>
        static public void SaveEntity(ZEntity en)
        {
            //save entity data
            List <IZComponent> coms    = en.GetComponents <IZComponent>();
            string             strData = en.ID.ToString() + "\n" + en.EType.ToString() + "\n";

            foreach (var c in coms)
            {
                strData += SaveComponentData(c);
            }

            string strFileName = en.Name + ".json";

            string entityPath = Application.dataPath + GetCurPoolEntityPath();

            System.IO.FileInfo file = new System.IO.FileInfo(entityPath + strFileName);
            StreamWriter       sw   = file.CreateText();

            sw.WriteLine(strData);
            sw.Close();
            sw.Dispose();
        }
		private void writeToFile(System.IO.FileInfo file, List<IJobDetail> jobDetails)
		{
			using (StreamWriter writer = file.CreateText())
			{
				XNamespace ns = "http://quartznet.sourceforge.net/JobSchedulingData";
				XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes")
					, new XElement(ns + "quartz"
						, new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance")
						, new XAttribute("version", "1.0")
						, new XAttribute("overwrite-existing-jobs", "true")
						)
					);
				foreach (IJobDetail detail in jobDetails)
				{
					doc.Root.Add(
							new XElement(ns + "job"
							, new XElement(ns + "job-detail"
							, new XElement(ns + "name", detail.Key.Name)
							, new XElement(ns + "group", detail.Key.Group)
							, new XElement(ns + "description", detail.Description)
							, new XElement(ns + "job-type", detail.JobType.FullName + "," + detail.JobType.Assembly.FullName)
						//TODO: Apparently volatile is no longer available. Check.
						//, new XElement(ns + "volatile", detail.Volatile)
							, new XElement(ns + "durable", detail.Durable)
							, new XElement(ns + "recover", detail.RequestsRecovery)
							, getJobDataMap(ns, detail.JobDataMap)
							)
							, getTriggers(ns, detail)
							)
						);
				}
				writer.Write(doc);
				writer.Flush();
				writer.Close();
			}
		}
        private void ActualizarePoze()
        {
            imagini.Clear();
            listaFisiere.Clear();
            Alignment Ax = comboBoxAx.SelectedItem as Alignment;

            if (Ax == null)
            {
                WF.MessageBox.Show((string)comboBoxAx.SelectedItem);
            }

            var fisiere = from string fisier in IO.Directory.GetFiles(textBoxDir.Text, "*.*", IO.SearchOption.AllDirectories)
                          where ".jpg.bmp.png.gif.jpeg.tiff".Contains(new IO.FileInfo(fisier).Extension.ToLower())
                          select fisier;


            if (fisiere.Count() == 0)
            {
                WF.MessageBox.Show("Directorul nu contine imagini!");
                return;
            }
            else
            {
                listaFisiere.AddRange(fisiere);
            }


            double lungimeAx = Ax.EndingStation - Ax.StartingStation;

            if (imaginiCheie.Count == 0)
            {
                imaginiCheie.Add((int)(Ax.StartingStation * 1000), fisiere.First());
                imaginiCheie.Add((int)(Ax.EndingStation * 1000), fisiere.Last());
                //double interval = (Ax.EndingStation - Ax.StartingStation) / (fisiere.Count() - 1);
                //for (int i = 0; i < fisiere.Count(); i++)
                //{
                //    double km = i * interval;
                //    //WF.MessageBox.Show(string.Format("Lungime ax: {0}\nInterval intre poze: {1}\nPozitia curenta:{2}", lungimeAx, interval, km)); //Raport individual imagini
                //    imagini.Add((int)(km * 1000), fisiere.ElementAt(i));
                //}
            }
            else if (imaginiCheie.Count == 1)
            {
                if (imaginiCheie.First().Key < (int)(Ax.EndingStation * 1000))
                {
                    imaginiCheie.Add((int)(Ax.EndingStation * 1000), fisiere.Last());
                }
                else
                {
                    imaginiCheie.Add((int)(Ax.StartingStation * 1000), fisiere.First());
                }
            }
            for (int j = 1; j < imaginiCheie.Count; j++)
            {
                double interval = (double)(imaginiCheie.ElementAt(j).Key - imaginiCheie.ElementAt(j - 1).Key) /
                                  (listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) - listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - 0);
                if (j == 1 && listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) > 0)
                {
                    for (int nr = 1; nr < listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - 1; nr++)
                    {
                        int index = listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - nr;
                        imagini.Add((int)(imaginiCheie.ElementAt(j - 1).Key - nr * interval), listaFisiere[index]);
                    }
                }
                for (int nr = 0; nr <= (listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) - listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) - 0); nr++)
                {
                    int index = listaFisiere.IndexOf(imaginiCheie.ElementAt(j - 1).Value) + nr;
                    int cheie = (int)(imaginiCheie.ElementAt(j - 1).Key + nr * interval);
                    if (!imagini.Keys.Contains(cheie))
                    {
                        imagini.Add((int)(imaginiCheie.ElementAt(j - 1).Key + nr * interval), listaFisiere[index]);
                    }
                }
                if (j == imaginiCheie.Count - 1 && listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) < listaFisiere.Count - 1)
                {
                    for (int nr = 1; nr < listaFisiere.Count - listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) - 0; nr++)
                    {
                        int index = listaFisiere.IndexOf(imaginiCheie.ElementAt(j).Value) + nr;
                        imagini.Add((int)(imaginiCheie.ElementAt(j).Key + nr * interval), listaFisiere[index]);
                    }
                }
            }


            //Scriere rezultat calibrare
            IO.FileInfo calibrare = new IO.FileInfo(textBoxDir.Text + @"\CALIBRARE.TXT");
            using (IO.StreamWriter SR = calibrare.CreateText())
            {
                foreach (int cheie in imagini.Keys)
                {
                    string fix = string.Empty;
                    if (imaginiCheie.Keys.Contains(cheie))
                    {
                        fix = "********";
                    }
                    SR.WriteLine(string.Format("Km: {0} -> {1}{2}", cheie, imagini[cheie], fix));
                }
            }



            //WF.Binding Bind = new WF.Binding("Value", imagini, "Keys");
            //trackBar1.DataBindings.Add(Bind);
            //    trackBar1.Minimum = (int)(Ax.StartingStation * 1000);
            //trackBar1.Maximum = (int)(Ax.EndingStation * 1000) + 1000;
            trackBar1.Minimum     = imagini.ElementAt(0).Key;
            trackBar1.Maximum     = imagini.Last().Key;
            trackBar1.Value       = trackBar1.Minimum;
            trackBar1.SmallChange = 1000;
            try
            {
                trackBar1.LargeChange = int.Parse(textBoxInterval.Text) * 1000;
            }
            catch
            {
                trackBar1.LargeChange = trackBar1.SmallChange * 5;
            }
            //trackBar1.SmallChange = (int)(interval * 1000);
            //trackBar1.LargeChange = int.Parse(textBoxInterval.Text) * 1000;
            //trackBar1.LargeChange = trackBar1.SmallChange * 5;
            trackBar1.TickFrequency = trackBar1.SmallChange;
            trackBar1.TickStyle     = System.Windows.Forms.TickStyle.BottomRight;

            textBoxKm.Leave    += TextBoxKm_Leave;
            textBoxKm.KeyPress += TextBoxKm_KeyPress;

            AfisarePoza();
        }
Example #36
0
 public static void writeToFile(string content, string fullPathFileName, bool appendToFile = false)
 {
     System.IO.FileInfo file = new System.IO.FileInfo(fullPathFileName);
     file.Directory.Create();
     using (var stream = file.Exists ? new StreamWriter(fullPathFileName, appendToFile) : file.CreateText())
     {
         stream.WriteLine(content);
     }
 }
Example #37
0
        public static void FileSplit(string filepath)
        {
            //获取打开的文件的名称及文件的目录
            FileInfo rx = new FileInfo(filepath);

            string[] a       = new string[] { "." };
            string[] rxname  = rx.Name.Split(a, StringSplitOptions.RemoveEmptyEntries);
            string   dirname = rx.DirectoryName;

            try
            {
                StreamReader sr = rx.OpenText();
                string       s  = sr.ReadToEnd();
                if (s == "")
                {
                    throw new nullException_server("the file is empty");
                }
                //if (s == null)
                //Console.WriteLine("file is empty");

                else
                {
                    //设置分割字符串对文件内容进行分割
                    string[] strseperator = new string[] { "begin_<points>", "begin_<grid>", "begin_<situation>" };
                    string[] result       = null;
                    result = s.Split(strseperator, StringSplitOptions.RemoveEmptyEntries);
                    int i = result.Length;
                    //创建分割的tx文件
                    for (int j = 1; j <= i; j++)
                    {
                        string             newpath = dirname + "\\" + rxname[0] + j.ToString() + "." + rxname[1];
                        System.IO.FileInfo newrx   = new System.IO.FileInfo(newpath);
                        using (StreamWriter sw = newrx.CreateText())
                        {
                            int m = result[j - 1].IndexOf("end_<points>");
                            int n = result[j - 1].IndexOf("end_<grid>");
                            if (m != -1)
                            {
                                sw.Write(strseperator[0]);
                                sw.Write(result[j - 1]);
                                sw.Close();
                            }
                            else
                            {
                                if (n != -1)
                                {
                                    sw.Write(strseperator[1]);
                                    sw.Write(result[j - 1]);
                                    sw.Close();
                                }
                                else
                                {
                                    sw.Write(strseperator[2]);
                                    sw.Write(result[j - 1]);
                                    sw.Close();
                                }
                            }
                        }
                    }
                }
                sr.Close();
            }
            catch (nullException_server e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw e;
            }
            File.Delete(filepath);
        }
Example #38
0
    //Function to write log file

    public static void Writefile_new(string strErrMesg, string strPath)
    {
        try
        {
            strPath = strPath + "//Log";
            string LogFilename         = "Log" + "_" + DateTime.Now.ToString("yyyyMMdd");
            System.Data.DataSet Dsfile = new System.Data.DataSet();
            if (System.IO.Directory.Exists(strPath) == false)
            {
                System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(strPath);
                dirinfo.Create();
                CreateNewXml(ref Dsfile);
                Dsfile.WriteXml(strPath + " \\XmlData.xml");

                System.IO.FileInfo     objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_0.log");
                System.IO.StreamWriter Tex     = objfile.CreateText();
                Tex.Write(strErrMesg + "\r\n");
                Tex.Close();
                System.GC.Collect();//
                return;
            }

            if (System.IO.File.Exists(strPath + "\\XmlData.xml") == true)
            {
                System.Data.DataRow[] dr;
                int FileIndex = 0;
                Dsfile.ReadXml(strPath + " \\XmlData.xml");
                dr = Dsfile.Tables[0].Select("SysDate ='" + DateTime.Now.ToString("dd-MM-yyyy") + "'");
                if (dr.Length > 0)
                {
                    FileIndex = Convert.ToInt32(dr[0]["Sysvalue"].ToString());
                }
                else
                {
                    Dsfile.Clear();
                    CreateNewXml(ref Dsfile);
                    Dsfile.WriteXml(strPath + "\\XmlData.xml");
                }

                if (System.IO.File.Exists(strPath + "\\" + LogFilename + "_" + FileIndex + ".log"))
                {
                    System.IO.FileInfo objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + FileIndex.ToString() + ".log");
                    if (objfile.Length > 500000)    //523636
                    {
                        System.IO.FileInfo     objfile1 = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + (FileIndex + 1).ToString() + ".log");
                        System.IO.StreamWriter Tex      = objfile1.CreateText();
                        Tex.Write(strErrMesg + "\r\n");
                        Tex.Close();
                        Dsfile.Tables[0].Rows[0]["Sysvalue"] = FileIndex + 1;
                        Dsfile.WriteXml(strPath + "\\XmlData.xml");
                        System.GC.Collect();
                    }
                    else
                    {
                        System.IO.StreamWriter Tex = objfile.AppendText();
                        Tex.Write(strErrMesg + "\r\n");
                        Tex.Close();
                        System.GC.Collect();
                    }
                }
                else
                {
                    System.IO.FileInfo     objfile = new System.IO.FileInfo(strPath + "\\" + LogFilename + "_" + FileIndex.ToString() + ".log");
                    System.IO.StreamWriter Tex     = objfile.CreateText();
                    Tex.Write(strErrMesg + "\r\n");
                    Tex.Close();
                    System.GC.Collect();
                }
            }
            else
            {
                CreateNewXml(ref Dsfile);
                Dsfile.WriteXml(strPath + "\\XmlData.xml");
                System.IO.FileInfo     objfile = new System.IO.FileInfo(strPath + LogFilename + "_0.log");
                System.IO.StreamWriter Tex     = objfile.CreateText();
                Tex.Write(strErrMesg + "\r\n");
                Tex.Close();
                System.GC.Collect();
            }
        }
        catch (Exception ex)
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(ex.Message);
        }
    }