他システムとの連携で固定長(改行区切り)ファイルフォーマットのテキスト出力が必要です。
構成は以下が1ブロックになっており
ヘッダ(300Byte)
明細(100Byte) ※複数行あり
トレーラ(50Byte)
各レコードの最後に改行コードが入ります(CR+LF)
StreamWriterで固定長テキストの出力方法が見つからず、
こちらのサイトを参考に
https://www.itlab51.com/?p=1984
以下のようにヘッダ、明細、トレーラの構造体を作成し、
「FileSystem.FilePut」で出力しましたが、
固定長のサイズが「FileSystem.FileOpen」で指定したヘッダデータのサイズになってしまいます。
ヘッダ、明細、トレーラを指定したサイズで出力する方法はございませんでしょうか?
宜しくお願い致します。
C#
.Net Framework 4.7.2を使用しています。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using Microsoft.VisualBasic; namespace テキストデータ作成 { public class 構造体 { //※見やすくする為、項目を削っています internal struct ヘッダデータ { [VBFixedString(2)] public string タグ; [VBFixedString(10)] public string 伝票番号; [VBFixedString(1)] public string 改行; } internal struct 明細データ { [VBFixedString(2)] public string タグ; [VBFixedString(13)] public string 商品コード; [VBFixedString(2)] public string 伝票行番号; [VBFixedString(50)] public string 商品名称; [VBFixedString(4)] public string 納品数; [VBFixedString(9)] public string 原価金額; [VBFixedString(9)] public string 原単価; [VBFixedString(1)] public string 改行; } internal struct トレーラデータ { [VBFixedString(2)] public string タグ; [VBFixedString(11)] public string 原価金額合計; [VBFixedString(1)] public string 改行; } public struct 出荷データ { public string 伝票番号 { get; set; } ...※その他項目は割愛します } } }
public bool テキスト出力(string ファイルパス, IReadOnlyCollection<構造体.出力データ> 出力データ) { try { 構造体.ヘッダデータ _ヘッダデータ = new 構造体.ヘッダデータ(); 構造体.明細データ _明細データ = new 構造体.明細データ(); 構造体.トレーラデータ _トレーラデータ = new 構造体.トレーラデータ(); FileSystem.FileOpen(1, @ファイルパス, OpenMode.Random, OpenAccess.Default, OpenShare.Default, Strings.Len(_ヘッダデータ)); string _伝票番号 = string.Empty; foreach (構造体.出力データ item in 出力データ) { //伝票番号が変わったらヘッダをテキストに出力 if (_伝票番号 != item.伝票番号) { //トレーラの出力予定 _ヘッダデータ.タグ = "HD"; _ヘッダデータ.伝票番号 = item.伝票番号; _ヘッダデータ.改行 = Environment.NewLine; FileSystem.FilePut(1, _ヘッダデータ); _伝票番号 = item.伝票番号; } _明細データ.タグ = "DT"; _明細データ.商品コード = item.商品コード; _明細データ.伝票行番号 = item.伝票行番号; _明細データ.商品名称 = item.商品名称; _明細データ.納品数量 = item.納品数量; _明細データ.原価金額 = item.原価金額; _明細データ.原単価 = item.原単価; _明細データ.改行 = Environment.NewLine; FileSystem.FilePut(1, _出荷明細データ); } FileSystem.FileClose(1); return true; } catch (Exception) { return false; throw; } finally { } }
回答1件
あなたの回答
tips
プレビュー