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


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

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


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

示例1: GenerateTypeScripts

        /// <summary>
        ///     Generate the CREATE TYPE and DROP TYPE statements.
        /// </summary>
        /// <param name="dtTypes"></param>
        /// <param name="dtSeq"></param>
        private static void GenerateTypeScripts(DataTable dtTypes, DataTable dtSeq)
        {
            var createPath = Path.Combine(
                _params[Parameters.OtherWorkPath].ToString(), Constants.CreateTypes);
            var dropPath = Path.Combine(
                _params[Parameters.OtherWorkPath].ToString(), Constants.CreateDropTypes);

            StreamWriter swCreate = null;
            StreamWriter swDrop = null;

            try
            {
                swCreate = new StreamWriter(createPath, false, Encoding.Default);
                swDrop = new StreamWriter(dropPath, false, Encoding.Default);

                swCreate.WriteBeginTrans();
                swDrop.WriteBeginTrans();

                // Write CREATE TYPE statements.
                foreach (DataRow row in dtTypes.Rows)
                {
                    var schema = row["schema_name"].ToString().Equals(Constants.PgDefaultSchema)
                        ? Constants.SsDefaultSchema
                        : row["schema_name"].ToString();

                    var typeName = "[" + schema + "].[" + row["type_name"] + "]";

                    swCreate.WriteLine("CREATE TYPE " + typeName);

                    var dataType = Postgres.SsDataType(row["regtype"].ToString());
                    swCreate.WriteLine(
                        "FROM [" + dataType + "]" +
                        GenerateColumnDimDef(row, dataType) + ";");
                    swCreate.WriteLine();

                    swDrop.WriteLine("DROP TYPE " + typeName + ";");
                }

                // Write CREATE SEQUENCE statements.
                foreach (DataRow row in dtSeq.Rows)
                {
                    var schema = row["schema_name"].ToString().Equals(Constants.PgDefaultSchema)
                        ? Constants.SsDefaultSchema
                        : row["schema_name"].ToString();
                    var seqName = "[" + schema + "].[" + row["seq_name"] + "]";
                    var dataType = Postgres.SsDataType(row["regtype"].ToString());

                    var maxValue = Postgres.GetMaxValByType(dataType);
                    var maxValueRec = (long) row["max_value"];
                    maxValue = maxValueRec > maxValue ? maxValue : maxValueRec;

                    swCreate.WriteLine("CREATE SEQUENCE " + seqName);
                    swCreate.WriteLine(Constants.Tab + "AS [" + dataType + "]");
                    swCreate.Write(Constants.Tab + "START WITH ");
                    swCreate.WriteLine(row["start_value"]);
                    swCreate.Write(Constants.Tab + "INCREMENT BY ");
                    swCreate.WriteLine(row["increment_by"]);
                    swCreate.Write(Constants.Tab + "MINVALUE ");
                    swCreate.WriteLine(row["min_value"]);
                    swCreate.Write(Constants.Tab + "MAXVALUE ");
                    swCreate.WriteLine(maxValue);

                    swCreate.WriteLine(
                        Constants.Tab + ((bool) row["is_cycled"] ? "CYCLE" : "NO CYCLE"));

                    swCreate.Write(Constants.Tab + "CACHE ");
                    swCreate.WriteLine(row["cache_value"]);

                    swCreate.WriteLine(";");
                    swCreate.WriteLine();

                    swDrop.WriteLine("DROP SEQUENCE " + seqName + ";");
                }

                swCreate.WriteCommitTrans();
                swDrop.WriteCommitTrans();
            }
            catch (Exception ex) {
                _log.WriteEx('E', Constants.LogTsType, ex);
            }
            finally
            {
                swCreate?.Dispose();
                swDrop?.Dispose();
            }
        }
开发者ID:mvrolijk,项目名称:ConvertPG2SS,代码行数:91,代码来源:ProcessPgSchema.cs

示例2: GenerateTableScripts

        /// <summary>
        ///     Generate the SQL Server scripts.
        /// </summary>
        /// <param name="schemaTable">DataTable with all the PostgreSQL schema/table/column info.</param>
        /// <param name="seqTable"></param>
        /// <param name="conn">PG connection.</param>
        private static void GenerateTableScripts(
			DataTable schemaTable,
			DataTable seqTable, 
			NpgsqlConnection conn)
        {
            var createPath = Path.Combine(
                _params[Parameters.OtherWorkPath].ToString(), Constants.CreateTables);
            var dropPath = Path.Combine(
                _params[Parameters.OtherWorkPath].ToString(), Constants.CreateDropTables);
            var truncPath = Path.Combine(
                _params[Parameters.OtherWorkPath].ToString(), Constants.CreateSTruncateTables);

            StreamWriter swCreate = null;
            StreamWriter swDrop = null;
            StreamWriter swTrunc = null;

            try
            {
                swCreate = new StreamWriter(createPath, false, Encoding.Default);
                swDrop = new StreamWriter(dropPath, false, Encoding.Default);
                swTrunc = new StreamWriter(truncPath, false, Encoding.Default);

                swCreate.WriteBeginTrans();
                swDrop.WriteBeginTrans();
                swTrunc.WriteBeginTrans();
                swCreate.PrepCreateTable();

                var savedSchema = "";
                var savedTable = "";
                var colInfo = new List<ColumnInfo>();

                foreach (DataRow row in schemaTable.Rows)
                {
                    var schema = row["schema_name"].ToString();
                    var table = row["table_name"].ToString();

                    // Schema or table changed: close table defenition.
                    if (!savedSchema.Equals(schema) || !savedTable.Equals(table))
                    {
                        if (!string.IsNullOrEmpty(savedTable))
                        {
                            CloseCreateTable(swCreate, colInfo);
                            UpdateSeqTable(colInfo, seqTable);
                            colInfo.Clear();
                        }
                        savedSchema = schema;
                        savedTable = table;

                        swCreate.OpenCreateTable(schema, table);
                        swDrop.WriteDropCommand(schema, table);
                        swTrunc.WriteTruncateCommand(schema, table);
                    }
                    else swCreate.WriteLine(",");

                    // Generate column definition.
                    ColumnInfo tmpColInfo;

                    swCreate.GenerateColumn(row, out tmpColInfo);
                    if (!string.IsNullOrEmpty(tmpColInfo.Schema))
                    {
                        colInfo.Add(tmpColInfo);
                    }
                }

                if (string.IsNullOrEmpty(savedSchema)) return;

                // Complete last writes.
                swCreate.CloseCreateTable(colInfo);
                swCreate.WriteTableDesc(conn);
                swCreate.WriteCommitTrans();
                swDrop.WriteCommitTrans();
                swTrunc.WriteCommitTrans();
            }
            catch (Exception ex) {
                _log.WriteEx('E', Constants.LogTsType, ex);
            }
            finally
            {
                swCreate?.Dispose();
                swDrop?.Dispose();
                swTrunc?.Dispose();
            }
        }
开发者ID:mvrolijk,项目名称:ConvertPG2SS,代码行数:89,代码来源:ProcessPgSchema.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: EntryPoint

		/// <summary>アプリケーションエントリーポイント。</summary>
		internal void EntryPoint(string[] args)
			{
			try
				{
				LogWriter = new StreamWriter( "WaveguideDesigner.log" );
				}
			catch { MessageBox.Show( "ログファイルを開けませんでした。ログ出力はされません。", "", MessageBoxButtons.OK, MessageBoxIcon.Error ); }
			LogMethodStart();

			CurrentUndoDepth = 0;
			FormulaEngine = new FormulaEngine();
			DoesUpdateShapeAuto = true;
			EnableUndoRedoStoring = true;
			if( args.Length != 0 ) OpenProject( args[0] );

			if( MainForm != null ) throw new InvalidOperationException();

			System.Windows.Forms.Application.EnableVisualStyles();
			System.Windows.Forms.Application.SetCompatibleTextRenderingDefault( false );
			MainForm = new Forms.MainForm();
			try
				{
				System.Windows.Forms.Application.Run( MainForm );
				}
			catch( Exception e )
				{
				WriteLog( e.ToString() );
				}

			LogMethodEnd();
			LogWriter?.Dispose();
			}
开发者ID:DaishiNakase,项目名称:WaveguideDesigner,代码行数:33,代码来源:Application.cs

示例5: AnalyzeMetadata

        private static void AnalyzeMetadata(StreamWriter writer, ulong startTime, ulong endTime, List<Metadata> sourceMetadata, List<Metadata> destinationMetadata, Dictionary<ulong, ulong> sourcePointMappings, Dictionary<ulong, ulong> destinationPointMappings, Dictionary<ulong, string> pointDevices, HashSet<ulong> frequencies)
        {
            writer?.WriteLine($"Meta-data dump for archive comparison spanning {new DateTime((long)startTime):yyyy-MM-dd HH:mm:ss} to {new DateTime((long)endTime):yyyy-MM-dd HH:mm:ss}:");
            writer?.WriteLine();
            writer?.WriteLine($"     Source Meta-data: {sourceMetadata.Count:N0} records");
            writer?.WriteLine($"Destination Meta-data: {destinationMetadata.Count:N0} records");

            string lastDeviceName = "";

            // Create point ID cross reference dictionaries
            foreach (Metadata sourceRecord in sourceMetadata.OrderBy(record => record.DeviceName).ThenBy(record => record.PointID))
            {
                ulong sourcePointID = sourceRecord.PointID;
                Metadata destinationRecord = destinationMetadata.FirstOrDefault(record => GetRootTagName(sourceRecord.PointTag).Equals(GetRootTagName(record.PointTag), StringComparison.OrdinalIgnoreCase));
                ulong destinationPointID = destinationRecord?.PointID ?? 0;
                sourcePointMappings[destinationPointID] = sourcePointID;
                destinationPointMappings[sourcePointID] = destinationPointID;
                pointDevices[sourcePointID] = sourceRecord.DeviceName;

                if (sourceRecord.SignalAcronym.Equals("FREQ", StringComparison.OrdinalIgnoreCase))
                    frequencies.Add(sourcePointID);

                if (!sourceRecord.DeviceName.Equals(lastDeviceName, StringComparison.OrdinalIgnoreCase))
                {
                    lastDeviceName = sourceRecord.DeviceName;
                    writer?.WriteLine();
                    writer?.WriteLine($"Measurements for device \"{lastDeviceName}\":");
                    writer?.WriteLine();
                }

                writer?.WriteLine($"Source \"{sourceRecord.PointTag}\" [{sourcePointID}] = Destination \"{destinationRecord?.PointTag}\" [{destinationPointID}]");
            }

            writer?.Dispose();
        }
开发者ID:GridProtectionAlliance,项目名称:openHistorian,代码行数:35,代码来源:ComparisonUtility.cs

示例6: HandleClientAsync


//.........这里部分代码省略.........

                        if (switched)
                        {
                            var setCurrent = Desktop.SetCurrent(inputDesktop);
                            if (setCurrent)
                            {
                                Console.WriteLine(
                                    $"Desktop switched from {LastDesktop} to {inputDesktop.DesktopName}");
                                LastDesktop = inputDesktop.DesktopName;
                                lastDesktopInput = inputDesktop;
                            }
                            else
                            {
                                lastDesktopInput.Close();
                            }
                        }
                    }
                    else
                    {
                        inputDesktop.Close();
                    }
                    var endpoint = await sr.ReadLineAsync();
                    if (string.IsNullOrEmpty(endpoint))
                    {
                        break;
                    }
                    string[] endpointArgs = { };
                    if (endpoint.Contains("|"))
                    {
                        var splitPoint = endpoint.Split('|');
                        endpointArgs = splitPoint[1].Split(',');
                        endpoint = splitPoint[0];
                    }
                    string response = null;
                    switch (endpoint)
                    {
                        case "fullframe":
                            var frameData = SendFullFrame();
                            response = frameData.Length == 0 ? "n" : Convert.ToBase64String(frameData);
                            break;
                        case "cleanframe":
                            var cleanFrameData = SendCleanFrame();
                            response = cleanFrameData.Length == 0 ? "n" : Convert.ToBase64String(cleanFrameData);
                            break;
                        case "ctrlaltdel":
                            HandleCtrlAltDel();
                            break;
                        case "rightdown":
                            HandleRightDown();
                            break;
                        case "rightup":
                            HandleRightUp();
                            break;
                        case "mousemove":
                            int x = Convert.ToInt16(endpointArgs[0], CultureInfo.InvariantCulture);
                            int y = Convert.ToInt16(endpointArgs[1], CultureInfo.InvariantCulture);
                            MoveMouse(x, y);
                            break;
                        case "mousedown":
                            HandleMouseDown();
                            break;
                        case "mousescroll":
                            HandleMouseScroll(endpointArgs[0]);
                            break;
                        case "mouseup":
                            HandleMouseUp();
                            break;
                        case "leftclick":
                            break;
                        case "rightclick":
                            HandleRightClick();
                            break;
                        case "keydown":
                            KeyDown(endpointArgs);
                            break;
                        case "keyup":
                            Keyup(endpointArgs);
                            break;
                    }
                    if (string.IsNullOrEmpty(response))
                    {
                        break;
                    }
                    await sw.WriteLineAsync(response);
                    await sw.FlushAsync();
                    await Task.Yield();
                }
            }
            catch (Exception aex)
            {
                var ex = aex.GetBaseException();
                Console.WriteLine("Client error: " + ex.Message);
            }
            finally
            {
                sr?.Dispose();

                sw?.Dispose();
            }
        }
开发者ID:Ulterius,项目名称:server,代码行数:101,代码来源:AgentServer.cs


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