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


C# FileInfo.OpenWrite方法代码示例

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


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

示例1: ChangePassButtonClick

        private void ChangePassButtonClick(object sender, RoutedEventArgs e)
        {
            var passStream = new FileInfo("C:\\Users\\Public\\pass.config");
            var passReader = new BinaryReader(passStream.OpenRead(), Encoding.Default);
            string realPass = passReader.ReadString();

            passReader.Close();
            if (oldPassBox.Password == realPass)
            {
                if (newPassBox.Password.Length >= 5 && (newPassBox.Password == newRPassBox.Password))
                {
                    realPass = newPassBox.Password;
                    var passWriter = new BinaryWriter(passStream.OpenWrite(), Encoding.Default);
                    passWriter.Write(realPass);
                }
                else if (newPassBox.Password.Length < 5)
                {
                    MessageBox.Show("Длина пароля меньше 5 символов. Для надежности задайте более длинный пароль");
                }
                else MessageBox.Show("Введенные пароли не совпадают, попробуйте снова");
            }
            else MessageBox.Show("Старый пароль введен неверно");

            File.SetAttributes("C:\\Users\\Public\\pass.config", FileAttributes.Hidden);
        }
开发者ID:ByShev,项目名称:userControlProgram,代码行数:25,代码来源:Window1.xaml.cs

示例2: CopyFile

        /// <summary>
        /// Copy the specified file.
        /// </summary>
        ///
        /// <param name="source">The file to copy.</param>
        /// <param name="target">The target of the copy.</param>
        public static void CopyFile(FileInfo source, FileInfo target)
        {
            try
            {
                var buffer = new byte[BufferSize];

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

                // perform the copy
                int packetSize = 0;

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

                // close the files after the copy
                ins0.Close();
                xout.Close();
            }
            catch (IOException e)
            {
                throw new EncogError(e);
            }
        }
开发者ID:CreativelyMe,项目名称:encog-dotnet-core,代码行数:39,代码来源:Directory.cs

示例3: Create

        /// <summary>
        /// Creates a file from a list of strings; each string is placed on a line in the file.
        /// </summary>
        /// <param name="TempFileName">Name of response file</param>
        /// <param name="Lines">List of lines to write to the response file</param>
        public static string Create(string TempFileName, List<string> Lines)
        {
            FileInfo TempFileInfo = new FileInfo( TempFileName );
            DirectoryInfo TempFolderInfo = new DirectoryInfo( TempFileInfo.DirectoryName );

            // Delete the existing file if it exists
            if( TempFileInfo.Exists )
            {
                TempFileInfo.IsReadOnly = false;
                TempFileInfo.Delete();
                TempFileInfo.Refresh();
            }

            // Create the folder if it doesn't exist
            if( !TempFolderInfo.Exists )
            {
                // Create the
                TempFolderInfo.Create();
                TempFolderInfo.Refresh();
            }

            using( FileStream Writer = TempFileInfo.OpenWrite() )
            {
                using( StreamWriter TextWriter = new StreamWriter( Writer ) )
                {
                    Lines.ForEach( x => TextWriter.WriteLine( x ) );
                }
            }

            return TempFileName;
        }
开发者ID:Tigrouzen,项目名称:UnrealEngine-4,代码行数:36,代码来源:ResponseFile.cs

示例4: Main

        static void Main(string[] args) {
            FileInfo f = new FileInfo("BinFile.dat");

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

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

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

            Console.WriteLine("Done!");
            Console.ReadLine();
        
        }
开发者ID:Geronimobile,项目名称:DotNetExamIntro,代码行数:25,代码来源:Program.cs

示例5: Main

		static void Main(string[] args)
		{
			if (args != null && args.Length > 0)
			{
				try
				{
					DirectoryInfo dir = new DirectoryInfo(args[0]);
					int days = (args.Length > 1) ? int.Parse(args[1]) : 30;

					PurgeFiles(dir, days);
				}
				catch (Exception ex)
				{
					// tell anybody listening that we exited with an error
					Environment.ExitCode = 1;

					FileInfo errLog = new FileInfo(GetCurDir() + "\\LFP_error.log");
					FileStream fs = errLog.OpenWrite();
					StreamWriter sw = new StreamWriter(fs);
					sw.WriteLine(ex.ToString());
					sw.Close();
					fs.Close();

				}

				Application.Exit();
			}
			else
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				Application.Run(new WinMain(args));

			}
		}
开发者ID:najnouj,项目名称:logfilemonitor,代码行数:35,代码来源:Program.cs

示例6: Dump

        public void Dump()
        {
            try
            {
                var schema = this.CurrentSchema;
                ContentRepository.ChangeProblems.Do(cp => schema.ApplyProblem(this.LastSchema, cp));

                DirectoryInfo di = new DirectoryInfo(Paths.AppDataPath + "\\ContentSchema");
                if (!di.Exists)
                    di.Create();
                FileInfo fi = new FileInfo(Paths.AppDataPath + "\\ContentSchema\\LastSchema.json");
                var sz = new JsonSerializer();
                sz.Formatting = Formatting.Indented;
                using (var stream = fi.OpenWrite())
                using (var writer = new StreamWriter(stream))
                using (var jsonTextWriter = new JsonTextWriter(writer))
                {
                    sz.Serialize(writer, schema);
                }
            }
            catch (Exception ex)
            {
                log.Error("Error creating content schema module dump: ", ex);
            }
        }
开发者ID:jamesej,项目名称:lynicon,代码行数:25,代码来源:ContentSchemaModule.cs

示例7: CreateFileTest

        public void CreateFileTest()
        {
            FileInfo fileToUpload = new FileInfo(Path.GetTempFileName());
            FileInfo downloadedFile = new System.IO.FileInfo(Path.GetTempFileName());

            // Set the file size
            using (var fstream = fileToUpload.OpenWrite())
            {
                fstream.SetLength(1024 * 1024 * 1);
            }

            dynamic ynode = (JsonConvert.DeserializeObject(yamlOptions) as dynamic);

            IClient sc = Blobstore.CreateClient("simple", ynode["blobstore"]["options"]);

            string objectId = sc.Create(fileToUpload);

            sc.Get(objectId, downloadedFile);

            Assert.IsTrue(fileToUpload.Length == downloadedFile.Length);

            fileToUpload.Delete();
            downloadedFile.Delete();

            //sc.Delete(objectId);
        }
开发者ID:UhuruSoftware,项目名称:bosh-dotnet,代码行数:26,代码来源:SimpleBlobstoreTest.cs

示例8: Main

        static void Main(string[] args)
        {
            Console.WriteLine("***** Fun with Binary Writers / Readers *****\n");

            // Open a binary writer for a file.
            FileInfo f = new FileInfo("BinFile.dat");
            using (BinaryWriter bw = new BinaryWriter(f.OpenWrite()))
            {
                // Print out the type of BaseStream.
                // (System.IO.FileStream in this case).
                Console.WriteLine("Base stream is: {0}", bw.BaseStream);

                // Create some data to save in the file
                double aDouble = 1234.67;
                int anInt = 34567;
                string aString = "A, B, C";

                // Write the data
                bw.Write(aDouble);
                bw.Write(anInt);
                bw.Write(aString);
            }

            Console.WriteLine("Done!");

            // Read the binary data from the stream.
            using (BinaryReader br = new BinaryReader(f.OpenRead()))
            {
                Console.WriteLine(br.ReadDouble());
                Console.WriteLine(br.ReadInt32());
                Console.WriteLine(br.ReadString());
            }

            Console.ReadLine();
        }
开发者ID:usedflax,项目名称:flaxbox,代码行数:35,代码来源:Program.cs

示例9: btn_del_Click

        private void btn_del_Click(object sender, EventArgs e)
        {
            FileInfo finfo = new FileInfo("\\log.txt");
            FileStream fs = finfo.OpenWrite();
            for (int i = 0; i < 130; i++)
            {
                if (IsRefD(Convert.ToInt32(this.textBox1.Text)))
                {

                        //�������洴�����ļ�������д������
                        StreamWriter w = new StreamWriter(fs);
                        //����д����������ʼλ��Ϊ�ļ�����ĩβ
                        w.BaseStream.Seek(0, SeekOrigin.End);
                        //д�롰Log Entry : ��
                        w.Write("\nLog Entry : ");
                        //д�뵱ǰϵͳʱ�䲢����
                        w.Write(
                            "{0} {1} \r\n",
                            DateTime.Now.ToLongTimeString(),
                            DateTime.Now.ToLongDateString());
                        //д����־���ݲ�����
                        w.Write("found ! " + i);
                        //�----------------��������
                        w.Write("------------------\n");
                        //��ջ��������ݣ����ѻ���������д�������
                        w.Flush();
                        //�ر�д������
                        w.Close();
                    return;
                }
                else
                    MessageBox.Show("Not found !" + i);
            }
        }
开发者ID:freudshow,项目名称:raffles-codes,代码行数:34,代码来源:Form1.cs

示例10: DownloadFile

		public static Task<FileInfo> DownloadFile(DirectoryInfo tempDir, Uri distributiveUri)
		{
			var httpClient = new HttpClient();
			var requestMessage = new HttpRequestMessage(HttpMethod.Get, distributiveUri);
			return httpClient
				.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead)
				.ContinueWith(
					getDistributiveTask => {
					                       	var response = getDistributiveTask.Result;
					                       	response.EnsureSuccessStatusCode();
					                       	var downloadingFileName =
					                       		string.Format("{0}.{1}.zip", Guid.NewGuid(), distributiveUri.Segments.LastOrDefault() ?? string.Empty);
					                       	var tempFile = new FileInfo(Path.Combine(tempDir.FullName, downloadingFileName));
					                       	var tempFileWriteStream = tempFile.OpenWrite();
					                       	return response.Content
					                       		.CopyToAsync(tempFileWriteStream)
					                       		.ContinueWith(
					                       			copyTask => {
					                       			            	copyTask.Wait(); // ensuring exception propagated (is it nessesary?)
					                       			            	tempFileWriteStream.Close();
					                       			            	return tempFile;
					                       			});
					})
				.Unwrap()
				.ContinueWith(
					downloadTask => {
					                	httpClient.Dispose();
					                	return downloadTask.Result;
					});
		}
开发者ID:artikh,项目名称:CouchDude.Bootstrapper,代码行数:30,代码来源:GetFileTask.cs

示例11: Serialize

		private NoSuchObjectDefinitionException Serialize(NoSuchObjectDefinitionException inputException)
		{
			NoSuchObjectDefinitionException deserializedException = null;
			string tempDir = Environment.GetEnvironmentVariable("TEMP");
			string tempFilename = tempDir + @"\foo.dat";
			FileInfo file = new FileInfo(tempFilename);
			try
			{
				Stream outstream = file.OpenWrite();
				new BinaryFormatter().Serialize(outstream, inputException);
				outstream.Flush();
				outstream.Close();
				Stream instream = file.OpenRead();
				deserializedException = new BinaryFormatter().Deserialize(instream) as NoSuchObjectDefinitionException;
				instream.Close();
			}
			finally
			{
				try
				{
					file.Delete();
				}
				catch
				{
				}
			}
			return deserializedException;
		}
开发者ID:ouyangyl,项目名称:MySpringNet,代码行数:28,代码来源:NoSuchObjectDefinitionExceptionTests.cs

示例12: CreateBat

 /// <summary>
 /// 生成bat文件,用於執行壓縮命令
 /// </summary>
 /// <param name="context"></param>
 /// <param name="excetion">異常信息</param>
 /// <returns></returns>
 public bool CreateBat(ref string excetion, CompressEnum compressEnum = CompressEnum.NORMAL)
 {
     try
     {
         FileInfo file = new FileInfo(fullExcuteBat);
         StringBuilder orderCmd = new StringBuilder("java -jar compiler.jar ");
         if (compressEnum == CompressEnum.WHITESPACE_ONLY)
         {
             orderCmd.Append(" --compilation_level WHITESPACE_ONLY ");
         }
         orderCmd.Append(" --js ");
         orderCmd.Append(this._tempFile);
         orderCmd.Append(" --js_output_file ");
         orderCmd.Append(this._compressFile);
         byte[] orderStream = Encoding.UTF8.GetBytes(orderCmd.ToString());
         using (FileStream filestream = file.OpenWrite())
         {
             filestream.Write(orderStream, 0, orderStream.Length);
         }
     }
     catch (Exception e)
     {
         excetion = e.Message;
         return false;
     }
     return true;
 }
开发者ID:seasun,项目名称:MyTestProjects,代码行数:33,代码来源:CompilerJarHelper.cs

示例13: Serialize

		public static void Serialize(FileInfo file, Action<GenericWriter> serializer)
		{
			file.Refresh();

			if (file.Directory != null && !file.Directory.Exists)
			{
				file.Directory.Create();
			}

			if (!file.Exists)
			{
				file.Create().Close();
			}
				
			file.Refresh();

			using (var fs = file.OpenWrite())
			{
				var writer = new BinaryFileWriter(fs, true);

				try
				{
					serializer(writer);
				}
				finally
				{
					writer.Flush();
					writer.Close();
				}
			}
		}
开发者ID:Crome696,项目名称:ServUO,代码行数:31,代码来源:Persistence.cs

示例14: WriteLogFile

 public void WriteLogFile(string input)
 {
     //定义文件信息对象
     FileInfo finfo = new FileInfo(path);
     //判断文件是否存在以及是否大于2K
     if (finfo.Exists && finfo.Length>2048)
     {
         finfo.Delete();
     }
     //创建只写文件流
     using (FileStream fs = finfo.OpenWrite())
     {
         //根据上面创建的文件流创建写数据流
         StreamWriter sw = new StreamWriter(fs);
         //设置写数据流的起始位置为文件流的末尾
         sw.BaseStream.Seek(0, SeekOrigin.End);
         //写入“Log Entry : ”
         sw.Write("\nLog Entry : ");
         //写入当前系统时间并换行
         sw.Write("{0} {1} \r\n", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString());
         //写入日志内容并换行
         sw.Write(input + "\r\n");        
         //写入------------------------------------“并换行
         sw.Write("------------------------------------\r\n");        
         //清空缓冲区内容,并把缓冲区内容写入基础流
         sw.Flush();       
         //关闭写数据流
         sw.Close();
     }
 }
开发者ID:ChenJingLei,项目名称:SmartEl,代码行数:30,代码来源:FileLog.cs

示例15: Main

        static void Main(string[] args)
        {
            var outputFile = new FileInfo("db_management.dat");

            if (outputFile.Exists)
                outputFile.Delete();

            using (var fileStream = outputFile.OpenWrite())
            {
                using (var streamWriter = new StreamWriter(fileStream))
                {
                    using (var dbContext = new TaskManagementContext())
                    {
                        foreach (var task in dbContext.Tasks.Where(t => t.Employee.Login != "slawek"))
                        {
                            var dbManagementRow = new DbManagementRow {
                                                                          Employee = task.Employee.Login,
                                                                          Area = task.Area.Name.GetEnum<AreaName>()
                                                                      };

                            foreach (var taskSkill in task.TaskSkills)
                                dbManagementRow.CheckValue(taskSkill.Skill.Name);

                            streamWriter.WriteLine(dbManagementRow.ToString());
                        }
                    }
                }
            }
        }
开发者ID:spolnik,项目名称:MSc_TaskManagementSystem_MachineLearning,代码行数:29,代码来源:Program.cs


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