OpenWrite() public method

public OpenWrite ( ) : FileStream
return FileStream
示例#1
0
 public void Store ()
 {
     Properties props = new Properties();
     props.Add ("foo", "this");
     props.Add ("bar", "is");
     props.Add ("baz", "it");
     FileInfo file = new FileInfo ("properties.test");
     try 
     {
         // write 'em out with the specified header...
         using (Stream cout = file.OpenWrite ()) 
         {
             props.Store (cout, "My Properties");
         }
     }
     finally 
     {
         try 
         {
             file.Delete ();
         } 
         catch (IOException)
         {
         }
     }
 }
示例#2
0
        static void Main(string[] args)
        {
            if (args == null || args.Length != 2)
                Console.WriteLine("Usage: <source folder> <destinaion file>");

            var source = new DirectoryInfo(args[0]);

            if (!source.Exists)
                throw new ApplicationException("Source folder does not exist");

            var destination = new FileInfo(args[1]);
            if (destination.Exists)
                throw new ApplicationException("Destination already exists");

            // mem-stream needs to be here for this to work?
            using (var destinationStream = destination.OpenWrite())
            using (var memStream = new MemoryStream())
            using (var lz4Stream = new LZ4Stream(destinationStream, CompressionMode.Compress, true, true))
            {
                using (var zipArchive = new ZipArchive(memStream, ZipArchiveMode.Create, true))

                    AddFilesToArchive(source, "", zipArchive);

                memStream.Position = 0;
                memStream.CopyTo(lz4Stream);
            }
        }
示例#3
0
        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);
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            FileStream file = null;
            var fileinfo = new FileInfo("TextFile1.txt");
            try
            {
                file = fileinfo.OpenWrite();
                file.WriteByte(0xF);
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("Could not locate the file");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                // Check for null because OpenWrite might have failed. 
                if (file != null)
                {
                    file.Close();
                }
            }

            Console.ReadKey();
        }
		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;
		}
示例#6
0
        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();
        }
 /// <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;
 }
		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;
					});
		}
示例#9
0
 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();
     }
 }
示例#10
0
		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();
				}
			}
		}
示例#11
0
        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);
        }
示例#12
0
        public async Task GenerateAudioAsync(VideoInfo video, System.IO.FileInfo Audiofile, AudioEncodingEnum AudioEncoding = AudioEncodingEnum.mp3, SoundTypeEnum Channels = SoundTypeEnum.Stereo, int AudioBitRate = 128, int AudioFrequency = 44100)
        {
            if (Audiofile.Exists)
            {
                Audiofile.Delete();
            }

            var FNWE          = video.File.FileNameWithoutExtension() + "_Audio";
            var TempDirectory = new System.IO.DirectoryInfo(video.File.Directory.FullName + @"\.Temp\" + DateTime.Now.Year + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00"));

            if (!TempDirectory.Exists)
            {
                TempDirectory.Create();
            }
            System.IO.FileInfo TempLogFile = new System.IO.FileInfo(TempDirectory.FullName + @"\" + FNWE + ".log");
            if (TempLogFile.Exists)
            {
                TempLogFile.Delete();
            }

            _logger.LogDebug("Grabbing Audio");
            var LogData = await RunFFMpegAsync("-i \"" + video.File.FullName + "\" -vn -acodec " + AudioEncoding.AudioFormat() + " -ab " + AudioBitRate + "k -ac " + System.Convert.ToInt32(Channels) + " -ar " + AudioFrequency + " -y \"" + Audiofile.FullName + "\"");

            var SW = new System.IO.StreamWriter(TempLogFile.OpenWrite());

            SW.Write(LogData);
            SW.Close();
            if (EncodingState == EncodingStateEnum.Not_Encoding)
            {
                throw new Exception("No audio was encoded.\n\r" + LogData);
            }
            _logger.LogDebug("Audio Grabbed");
            Audiofile.Refresh();
        }
示例#13
0
        public async Task GenerateImageAsync(VideoInfo video, System.IO.FileInfo ImageFile, int Width, int Height)
        {
            if (ImageFile.Exists)
            {
                ImageFile.Delete();
            }

            var FNWE          = video.File.FileNameWithoutExtension() + "_Image";
            var TempDirectory = new System.IO.DirectoryInfo(video.File.Directory.FullName + @"\.Temp\" + DateTime.Now.Year + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00"));

            if (!TempDirectory.Exists)
            {
                TempDirectory.Create();
            }
            System.IO.FileInfo TempLogFile = new System.IO.FileInfo(TempDirectory.FullName + @"\" + FNWE + ".log");
            if (TempLogFile.Exists)
            {
                TempLogFile.Delete();
            }

            _logger.LogDebug("Grabbing Image");
            var LogData = await RunFFMpegAsync("-i \"" + video.File.FullName + "\" -an -ss 00:00:07 -an -s " + Width + "x" + Height + " -r 1 -vframes 1 -f image2 -y \"" + ImageFile.FullName + "\"");

            var SW = new System.IO.StreamWriter(TempLogFile.OpenWrite());

            SW.Write(LogData);
            SW.Close();

            _logger.LogDebug("Image Grabbed");
            ImageFile.Refresh();
        }
示例#14
0
        public string ProxyResource(Uri uri)
        {
            if (_tempFileMap.ContainsKey(uri)) {
                return _tempFileMap[uri];
            }

            StreamResourceInfo streamInfo = Application.GetResourceStream(uri);
            if (streamInfo != null) {

                string strUri = uri.AbsolutePath;
                String tempFile = NewFilename(strUri.Substring(strUri.LastIndexOf(".")));
                FileInfo file = new FileInfo(tempFile);

                Logger.Debug("Creating temp file {0} from resource {1}", tempFile, uri.AbsolutePath);

                using(streamInfo.Stream) {
                    using(Stream dest = file.OpenWrite()) {
                        byte[] buffer = new byte[1024];
                        int bytes;
                        while((bytes = streamInfo.Stream.Read(buffer, 0, buffer.Length)) > 0) {
                            dest.Write(buffer, 0, bytes);
                        }
                    }
                }

                _tempFileMap[uri] = tempFile;
                return tempFile;
            }
            return null;
        }
示例#15
0
        static void Main(string[] args)
        {
            Employee empl = new Employee("Müller", 28, 1, 10000, "ssn-0001");

              // Save it with a BinaryFormatter
              FileInfo f = new FileInfo(@"L7U2_EmployeeBin.txt");
              using (BinaryWriter bw = new BinaryWriter(f.OpenWrite()))
              {
            bw.Write(empl.Age);
            bw.Write(empl.ID);
            bw.Write(empl.Name);
            bw.Write(empl.Pay);
            bw.Write(empl.SocialSecurityNumber);
              }

              // Save it with a SoapFormatter
              using (FileStream str = File.Create("L7U2_EmployeeSoap.txt"))
              {
            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(str, empl);
              }

              // Save it with a XmlSerializer
              XmlSerializer SerializerObj = new XmlSerializer(typeof(Employee));

              TextWriter WriteFileStream = new StreamWriter(@"L7U2_EmployeeXml.txt");
              SerializerObj.Serialize(WriteFileStream, empl);

              WriteFileStream.Close();
        }
        private static void ExtractFileFromAssembly(Assembly currentAssembly, string resourceName, string saveAsName)
        {
            FileInfo fileInfoOutputFile = new FileInfo(saveAsName);
            //CHECK IF FILE EXISTS AND DO SOMETHING DEPENDING ON YOUR NEEDS
            if (fileInfoOutputFile.Exists)
            {
            }

            FileStream streamToOutputFile = fileInfoOutputFile.OpenWrite();
            //GET THE STREAM TO THE RESOURCES
            Stream streamToResourceFile =
                                currentAssembly.GetManifestResourceStream(resourceName);

            //---------------------------------
            //SAVE TO DISK OPERATION
            //---------------------------------
            const int size = 4096;
            byte[] bytes = new byte[4096];
            int numBytes;
            while ((numBytes = streamToResourceFile.Read(bytes, 0, size)) > 0)
            {
                streamToOutputFile.Write(bytes, 0, numBytes);
            }

            streamToOutputFile.Close();

            streamToResourceFile.Close();

            if (!File.Exists(saveAsName))
            {
                MessageBox.Show("Not found " + saveAsName);
            }
        }
示例#17
0
        /// <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);
            }
        }
        /// <summary>
        /// Executes the tests.
        /// </summary>
        public static void Test()
        {
            TagsTableCollectionIndex index = new TagsTableCollectionIndex();

            // first fill the index.
            ITagCollectionIndexTests.FillIndex(index, 100000);

            // serialize the index.
            FileInfo testFile = new FileInfo(@"test.file");
            testFile.Delete();
            Stream writeStream = testFile.OpenWrite();
            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                "Serializing blocked file....");
            TagIndexSerializer.SerializeBlocks(writeStream, index, 100);
            writeStream.Flush();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testFile.Length / 1024));

            // deserialize the index.
            Stream readStream = testFile.OpenRead();
            ITagsCollectionIndexReadonly readOnlyIndex = TagIndexSerializer.DeserializeBlocks(readStream);

            // test access.
            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                "Started testing random access....");
            ITagCollectionIndexTests.TestRandomAccess("Blocked", readOnlyIndex, 1000);

            readStream.Dispose();
            testFile.Delete();
        }
示例#19
0
		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));

			}
		}
        private void ReemplazarRutasArchivoEnDestino(string RutaDestino, FileInfo file, bool reemplazar)
        {
            DirectoryInfo destino = new DirectoryInfo(RutaDestino);

            var newfile = new FileInfo(Path.Combine(destino.FullName, file.Name));

            using (Stream stream = newfile.OpenWrite())

            using (StreamReader sr = new StreamReader(file.FullName))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    ReglasDeReemplazo replaceArrumacos = new ReglasDeReemplazo(_nuevoPath);
                    while (sr.Peek() >= 0)
                    {

                        string line = sr.ReadLine();

                        foreach (var item in replaceArrumacos.Reglas)
                        {
                            if(reemplazar)
                                line = line.Replace(item.Key, item.Value);
                        }

                        writer.WriteLine(line);

                    }
                }
            }
        }
示例#21
0
        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();
        
        }
示例#22
0
 public static void WriteTo(FileInfo file)
 {
     using (var w = new StreamWriter(file.OpenWrite()))
     {
         w.Write("This information is very important!");
     }
 }
        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);
        }
示例#24
0
 public void JsonFileReaderTest()
 {
     // ReSharper disable once AssignNullToNotNullAttribute
     var exampleFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "file-reader-test.json");
     var exampleFile = new FileInfo(exampleFilePath);
     if (exampleFile.Exists) exampleFile.Delete();
     FileStream fileStream = null;
     try
     {
         fileStream = exampleFile.OpenWrite();
         using (var writer = new StreamWriter(fileStream))
         {
             fileStream = null;
             writer.Write(Settings);
         }
         var reader = new JsonFileSettingsReader();
         reader.SetPath(exampleFilePath);
         var result = reader.Read<ExampleSettings>();
         result.ShouldBeEquivalentTo(settingsExepted);
     }
     finally
     {
         fileStream?.Dispose();
     }
 }
示例#25
0
        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);
            }
        }
        // yuehan start: 保存 baml 到 xaml 文件
        public override bool Save(DecompilerTextView textView)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = Path.GetFileName(DecompilerTextView.CleanUpName(base.Text as string));
            dlg.FileName = Regex.Replace(dlg.FileName, @"\.baml$", ".xaml", RegexOptions.IgnoreCase);
            if (dlg.ShowDialog() == true)
            {
                // 反编译 baml 文件
                var baml = this.Data;
                var asm = this.Ancestors().OfType<AssemblyTreeNode>().FirstOrDefault().LoadedAssembly;
                baml.Position = 0;
                var doc = LoadIntoDocument(asm.GetAssemblyResolver(), asm.AssemblyDefinition, baml);
                var xaml = doc.ToString();

                // 保存 xaml
                FileInfo fi = new FileInfo(dlg.FileName);
                if (fi.Exists) fi.Delete();

                using (var fs = fi.OpenWrite())
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);
                    sw.Write(xaml);
                    sw.Flush();
                    sw.Close();
                }
            }
            return true;
        }
        public static void saveHtmldoc(string name, string path , string htmlSource, string description)
        {
            path = "c:";
            try
            {
                ///指定要生成的HTML文件
                string fname = path + "//" + name+"--" + DateTime.Now.ToString("yyyymmddhhmmss") + ".html";

                ///创建文件信息对象
                FileInfo finfo = new FileInfo(fname);

                ///以打开或者写入的形式创建文件流
                using(FileStream fs = finfo.OpenWrite())
                {
                   ///根据上面创建的文件流创建写数据流
                    StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));

                    ///把新的内容写到创建的HTML页面中
                    sw.WriteLine(htmlSource);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch(Exception err)
            {
                AllForms.m_frmLog.AppendToLog("tsFile_ItemClicked\r\n" + err.ToString());
            }
        }
        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());
                        }
                    }
                }
            }
        }
示例#29
0
        private void Render(JavaContext context, string templateName)
        {
            var template = templateLoader.Load(templateName);
            Enforce.IsNotNull(template, string.Format("No template for '{0}' found!", templateName));
            template.Add("context", context);

            var tweakMap = new Dictionary<string, bool>();
            var tweakValues = Enum.GetValues(typeof(GeneratorTweak));
            foreach (var tweak in tweakValues)
            {
                tweakMap.Add(tweak.ToString(), config.ContainsTweak((GeneratorTweak)tweak));
            }
            template.Add("tweaks", tweakMap);

            var packages = context.JavaPackage.Split('.');
            DirectoryInfo folder = outputFolder;

            foreach (string pkg in packages)
            {
                folder = folder.CreateSubdirectory(pkg);
            }

            var file = new FileInfo(Path.Combine(folder.FullName, context.JavaName + ".java"));
            using (Stream stream = file.OpenWrite())
            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
            {
                template.Write(new AutoIndentWriter(writer));
                writer.Flush();
            }
        }
示例#30
0
        /// <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;
        }
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static void TestSerialization(string name, string pbfFile)
        {
            FileInfo testFile = new FileInfo(string.Format(@".\TestFiles\{0}", pbfFile));
            Stream stream = testFile.OpenRead();
            PBFOsmStreamSource source = new PBFOsmStreamSource(stream);

            FileInfo testOutputFile = new FileInfo(@"test.routing");
            testOutputFile.Delete();
            Stream writeStream = testOutputFile.OpenWrite();

            CHEdgeGraphFileStreamTarget target = new CHEdgeGraphFileStreamTarget(writeStream,
                Vehicle.Car);
            target.RegisterSource(source);

            PerformanceInfoConsumer performanceInfo = new PerformanceInfoConsumer("CHSerializer");
            performanceInfo.Start();
            performanceInfo.Report("Pulling from {0}...", testFile.Name);

            var data = CHEdgeGraphOsmStreamTarget.Preprocess(
                source, new OsmRoutingInterpreter(), Vehicle.Car);

            TagsCollectionBase metaData = new TagsCollection();
            metaData.Add("some_key", "some_value");
            var routingSerializer = new CHEdgeDataDataSourceSerializer(true);
            routingSerializer.Serialize(writeStream, data, metaData);

            stream.Dispose();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("CHSerializer", OsmSharp.Logging.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testOutputFile.Length / 1024));

            performanceInfo.Stop();
        }
示例#32
0
 public void Upload(byte[] mp3FileData)
 {
     currentFile = new FileInfo(Path.Combine(Path.GetTempPath(), random.Next() + ".mp3"));
     FileStream fs = currentFile.OpenWrite();
     fs.Write(mp3FileData, 0, mp3FileData.Length);
     fs.Close();
 }
示例#33
0
        static public void WriteFile(string filename, byte[] dataText)
        {
            try
            {
                System.IO.FileInfo finfo = new System.IO.FileInfo(filename);
                FileStream         fs    = finfo.OpenWrite();
                fs.Write(dataText, 0, dataText.Length);
                fs.Close();
                return;
            }

            catch (Exception)
            {
                return;
            }
        }