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


C# StreamWriter.?.Close方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            var connectionString = $"Data Source = \"{SdfFilePath}\"";

            SqlCeConnection connection = null;
            SqlCeCommand command = null;
            SqlCeDataReader reader = null;
            StreamWriter csvWriter = null;

            try
            {
                connection = new SqlCeConnection(connectionString);
                connection.Open();

                var query = "SELECT * FROM Petitioners";
                command = new SqlCeCommand(query, connection);
                reader = command.ExecuteReader();

                csvWriter = new StreamWriter($"{CsvFilePath}", false, Encoding.Default);

                csvWriter.WriteLine(Enumerable.Range(0, reader.FieldCount)
                    .Select(i => $"\"{reader.GetName(i)}\"")
                    .Aggregate((current, next) => $"{current},{next}"));

                while (reader.Read())
                {
                    csvWriter.WriteLine(Enumerable.Range(0, reader.FieldCount)
                        .Select(i => String.Format("\"{0}\"",
                            reader.GetValue(i)
                                .ToString()
                                .Replace(',', '_')
                                .Replace('\"', '_')))
                        .Aggregate((current, next) => $"{current},{next}"));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            finally
            {
                csvWriter?.Close();
                reader?.Close();
                command?.Dispose();
                connection?.Close();
            }

            Console.WriteLine($"{Environment.NewLine}Press any key to exit.");
            Console.ReadKey();
        }
开发者ID:greymind,项目名称:DatabaseConverters,代码行数:50,代码来源:Program.cs

示例2: Run

		public override void Run()
		{
			taskInterface.SetStatus("Deleting Old Src");

			if (Directory.Exists(FullSrcDir))
				Directory.Delete(FullSrcDir, true);

			var baseFiles = Directory.EnumerateFiles(FullBaseDir, "*", SearchOption.AllDirectories);
			var patchFiles = Directory.EnumerateFiles(FullPatchDir, "*", SearchOption.AllDirectories);

		    var removedFileList = Path.Combine(FullPatchDir, DiffTask.RemovedFileList);
            var removedFiles = File.Exists(removedFileList) ? new HashSet<string>(File.ReadAllLines(removedFileList)) : new HashSet<string>();

			var copyItems = new List<WorkItem>();
			var patchItems = new List<WorkItem>();
			var formatItems = new List<WorkItem>();

			foreach (var file in baseFiles)
			{
				var relPath = RelPath(FullBaseDir, file);
				if (DiffTask.excluded.Any(relPath.StartsWith) || removedFiles.Contains(relPath))
					continue;

				var srcPath = Path.Combine(FullSrcDir, relPath);
				copyItems.Add(new WorkItem("Copying: " + relPath, () => Copy(file, srcPath)));

				if (format != null && file.EndsWith(".cs"))
					formatItems.Add(new WorkItem("Formatting: " + relPath,
						() => FormatTask.Format(srcPath, format, taskInterface.CancellationToken())));
			}

			foreach (var file in patchFiles)
			{
				var relPath = RelPath(FullPatchDir, file);
				if (relPath.EndsWith(".patch"))
					patchItems.Add(new WorkItem("Patching: " + relPath, () => Patch(relPath)));
				else if (relPath != DiffTask.RemovedFileList)
					copyItems.Add(new WorkItem("Copying: " + relPath, () => Copy(file, Path.Combine(FullSrcDir, relPath))));
			}

			taskInterface.SetMaxProgress(copyItems.Count + formatItems.Count + patchItems.Count);
			ExecuteParallel(copyItems, false);
			ExecuteParallel(formatItems, false);

			try
			{
				CreateDirectory(Program.LogDir);
				logFile = new StreamWriter(Path.Combine(Program.LogDir, "patch.log"));
				ExecuteParallel(patchItems, false);
			}
			finally {
			    logFile?.Close();
			}

		    cutoff.Set(DateTime.Now);
		}
开发者ID:JavidPack,项目名称:TerraCustom,代码行数:56,代码来源:PatchTask.cs

示例3: ExportToCSV


//.........这里部分代码省略.........
      StreamWriter writer;
      StreamWriter dbWriter = null;
      StreamWriter pageWriter = null;
      Dictionary<UInt32, StreamWriter> files = new Dictionary<uint, StreamWriter>();
      byte[] newLineBytes = Page.StringToByteArray(Environment.NewLine);
      try
      {
        List<Database> dbs = session.OpenAllDatabases();
        string filePath = "Database.csv";
        FileStream dbStream = new FileStream(Path.Combine(directory, filePath), FileMode.Create);
        dbWriter = new StreamWriter(dbStream);
        dbWriter.WriteLine($"Number{fieldSeperator}Name");
        filePath = "Page.csv";
        FileStream pageStream = new FileStream(Path.Combine(directory, filePath), FileMode.Create);
        pageWriter = new StreamWriter(pageStream);
        pageWriter.WriteLine($"DatabaseNumber{fieldSeperator}PageNumber{fieldSeperator}NumberOfSlots{fieldSeperator}FirstFreeSlot{fieldSeperator}Version{fieldSeperator}Encryption{fieldSeperator}Compression{fieldSeperator}TypeVersion");
        foreach (Database db in dbs)
        {
          if (db != null && db.DatabaseNumber != 4 && db.DatabaseNumber != 0) // we skip the license database because we can't restore it without encryption key
          {
            dbWriter.WriteLine(db.DatabaseNumber.ToString() + fieldSeperator + "\"" + db.Name + "\"");
            foreach (Page page in db)
            {
              if (page.PageNumber > 0)
              {
                pageWriter.WriteLine(page.Database.DatabaseNumber.ToString() + fieldSeperator +
                                     page.PageNumber + fieldSeperator +
                                     page.PageInfo.NumberOfSlots + fieldSeperator +
                                     page.PageInfo.FirstFreeSlot + fieldSeperator +
                                     page.PageInfo.VersionNumber + fieldSeperator +
                                     page.PageInfo.Encryption + fieldSeperator +
                                     page.PageInfo.Compressed + fieldSeperator +
                                     page.PageInfo.ShapeNumber);
                foreach (IOptimizedPersistable pObj in page)
                {
                  TypeVersion tv = pObj.Shape;
                  if (!files.TryGetValue(tv.ShortId, out writer))
                  {
                    Type type = tv.VelocityDbType.Type;
                    string typeName = type == null ? "Unknown (not loaded)" : type.ToGenericTypeString();
                    string[] illegal = new string[] { "<", ">" };
                    foreach (var c in illegal)
                    {
                      typeName = typeName.Replace(c, string.Empty);
                    }
                    filePath = typeName + pObj.Shape.ShortId + ".csv";
                    FileStream fStream = new FileStream(Path.Combine(directory, filePath), FileMode.Create);
                    writer = new StreamWriter(fStream);
                    files[pObj.Shape.ShortId] = writer;
                    List<DataMember> members = tv.GetDataMemberList();
                    byte[] bytes = Page.StringToByteArray($"id{fieldSeperator}"); // special transient member
                    fStream.Write(bytes, 0, bytes.Length);
                    if (tv.IsString)
                    {
                      bytes = Page.StringToByteArray($"String");
                      fStream.Write(bytes, 0, bytes.Length);
                    }
                    else
                    {
                      int l = members.Count;
                      for (int i = 0; i < l; i++)
                        {
                          if (i + 1 < l)
                            bytes = Page.StringToByteArray(members[i].FieldName + fieldSeperator);
                          else
                            bytes = Page.StringToByteArray(members[i].FieldName);
                          fStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                    //writer.Write("\"" + pObj.Shape.velocityDbType.type.AssemblyQualifiedName + "\"");
                    writer.WriteLine();
                  }
                  string aRow = tv.EncodeForCsv(pObj, page.PageInfo, session);
                  writer.WriteLine(aRow);
                }
              }
            }
          }
        }
      }
      finally
      {
        foreach (StreamWriter s in files.Values)
        {
#if WINDOWS_UWP
          s.Flush();
          s.Dispose();
#else
          s.Close();
#endif
        }
#if WINDOWS_UWP
        pageWriter?.Dispose();
        dbWriter?.Dispose();
#else
        pageWriter?.Close();
        dbWriter?.Close();
#endif
      }
    }
开发者ID:VelocityDB,项目名称:VelocityDB,代码行数:101,代码来源:ImportExportCsv.cs

示例4: DetermineKeyPoints


//.........这里部分代码省略.........
            float x, y;
            double abs;

            for (int t = 0; t < results.Length; t++)
            {
                for (int freq = LOWER_LIMIT; freq < UPPER_LIMIT - 1; freq++)
                {
                    // Get the magnitude:
                    x = results[t][freq].X;
                    y = results[t][freq].Y;
                    abs = Math.Sqrt(x * x + y * y);
                    double mag = Math.Log(abs + 1);

                    // Find out which range we are in:
                    int index = GetIndex(freq);

                    // Save the highest magnitude and corresponding frequency:
                    if (mag > highscores[t, index])
                    {
                        highscores[t, index] = mag;
                        recordPoints[t, freq] = 1;
                        points[t, index] = freq;
                    }
                }

                try
                {
                    for (int k = 0; k < 5; k++)
                    {
                        outFile.Write("" + highscores[t, k] + ";"
                                      + recordPoints[t, k] + "\t");
                    }
                    outFile.Write("\n");
                    outFile.Flush();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                long h = hash(points[t, 0], points[t, 1], points[t, 2],
                    points[t, 3]);

                if (isMatching)
                {
                    List<DataPoint> listPoints;

                    if ((listPoints = db.GetDataPoints(h)) != null)
                    {
                        foreach (DataPoint dP in listPoints)
                        {
                            int offset = Math.Abs(dP.time - t);
                            Dictionary<int, int> tmpMap = null;
                            if ((tmpMap = db.GetSong(dP.songId)) == null)
                            {
                                tmpMap = new Dictionary<int, int>();
                                tmpMap[offset] = 1;
                                db.InsertSong(dP.songId, tmpMap);
                            }
                            else
                            {
                                int count = tmpMap[offset];
                                if (count == null)
                                {
                                    tmpMap[offset] = 1;
                                }
                                else
                                {
                                    tmpMap[offset] = count + 1;
                                }
                            }
                        }
                    }
                }
                else
                {
                    List<DataPoint> listPoints = null;
                    if ((listPoints = db.GetDataPoints(h)) == null)
                    {
                        listPoints = new List<DataPoint>();
                        DataPoint point = new DataPoint() { songId = (int)songId, time = t };
                        listPoints.Add(point);
                        db.InsertDataPoint(h, listPoints);
                    }
                    else
                    {
                        DataPoint point = new DataPoint() { songId = (int)songId, time = t };
                        listPoints.Add(point);
                    }
                }
            }
            try
            {
                outFile?.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine(e);
            }
        }
开发者ID:titu1994,项目名称:Music-Recognition,代码行数:101,代码来源:AudioManager.cs

示例5: Main

        static void Main(string[] args)
        {
            _handle = GetConsoleWindow();
            ShowWindow(_handle, SwHide); //replace SwHide with SwShow to show console window

            #region check autostart registry key

            Directory.SetCurrentDirectory(Application.ExecutablePath.Remove(Application.ExecutablePath.LastIndexOf('\\')));

            // path to the key where Windows looks for startup applications
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (rkApp == null)
                WriteLog("Error while loading autostart registry key.");

            if (rkApp != null && !IsStartupItem(rkApp))
            {
                // add the value in the registry so that the application runs at startup
                rkApp.SetValue("ShutdownBroadcastListener", Application.ExecutablePath);
                WriteLog("The registry key was set successfully. The client will start automatically on next pc start.");
            }

            #endregion

            #region load configuration

            _logSw = new StreamWriter("log.txt", true);

            try
            {
                LoadData();
            }
            catch (IOException)
            {
                WriteLog("Error while loading configuartion: config.txt wasn't found");
                _logSw?.Close();
                return;
            }
            catch (ApplicationException ae)
            {
                WriteLog(ae.Message);
                _logSw?.Close();
                return;
            }

            _logSw?.Close();

            WriteLog("configuation loaded successfully");
            WriteLog("server ip = " + _serverIp);
            WriteLog("secret = " + _secret);
            WriteLog("port = " + _port);

            #endregion

            BeginReceive();

            //close application when "cancel" is entered
            while (true)
            {
                string l = Console.ReadLine();
                if (l == "cancel")
                    break;
            }
        }
开发者ID:tranquvis,项目名称:ShutdownBroadcast,代码行数:63,代码来源:Program.cs

示例6: Write

        /// <summary>
        /// </summary>
        /// <exception cref="AggregateException">The exception that contains all the individual exceptions thrown on all threads.</exception>
        /// <exception cref="UnauthorizedAccessException">Access is denied. </exception>
        /// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive). </exception>
        /// <exception cref="IOException">
        ///     path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.
        /// </exception>
        /// <exception cref="SecurityException">The caller does not have the required permission. </exception>
        public void Write()
        {
            var pathsForSetting = new ConcurrentBag<FileWatcherHelper>();

            Parallel.ForEach(ListFromFileSystem(),
                name =>
                {
                    var file = new FileInfo(name);
                    var fileWatcherHelper = new FileWatcherHelper
                                            {
                                                Path = name,
                                                LastWriteTime = file.LastWriteTime
                                            };
                    pathsForSetting.Add(fileWatcherHelper);
                });
            StreamWriter streamWriter = null;
            try
            {
                var serialiser = new XmlSerializer(typeof(List<FileWatcherHelper>));
                streamWriter = new StreamWriter(_xmlPath);
                serialiser.Serialize(streamWriter, pathsForSetting.ToList());
            }
            finally
            {
                streamWriter?.Close();
            }
        }
开发者ID:evilbaschdi,项目名称:FileWatcher,代码行数:36,代码来源:Worker.cs


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