How to Read and Write Text File Using StreamReader and StreamWriter in Dynamics Ax



Description:-

AX provides several ways of writing files. Depending upon scenario, you can use one. Apart from AX native filing, you can also use .NET interop to call .NET classes for reading/writing files. We will be showing few classes which are provided by AX for writing files.

StreamReader and StreamWriter

Implements a TextReader that reads characters from a byte stream in a particular encoding.Implements a TextWriter for writing characters to a stream in a particular encoding.

1
2
3
4
5
6
7
8
9
Length: Gets the length (in bytes) of the stream.
Position: Gets or sets the current position in the stream for reading and writing operations.
Seek(): Sets the position within the stream.
Flush(): Clears any buffers within the stream and forces changes to be written to the underlying system or device. Some streams have the AutoFlush property for flushing automatically any change.
Close(): Closes the stream and releases any resources associated with it. !!! Remember always close the stream !!!
Read(): Performs a sequential read of a specified number of bytes from the current position and updates the position to the end of the read upon completion of the operation.
ReadByte(): Performs the read of a single byte and updates the position by moving it by one.
Write(): Writes information to the stream as a number of bytes and updates the current position to reflect the new write position.
WriteByte(): Writes a single byte to the stream and updates the position.

There are a lot of streams, some of them:


FileStream
MemoryStream
CryptoStream
NetworkStream
GZipStream

The File class
The File class provides methods for easy writing and reading operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
Copy(): Copies a file to a new file. !!! The new file must not exist or an event will be thrown. !!!
Move(): Moves a file from one place to another. !!! The target file must not exist or an event will be thrown. !!!
Delete(): Deletes a file. !!! None exception is throw if file doesn't exists !!!
Exists(): Returns true if a file exists.
AppendText(): Opens a file (or creates a new file if one does not exist) and returns a StreamWriter that is prepared to allow text to be appended to the file.
CreateText(): Creates or opens a file and returns a StreamWriter object that is ready to have text written into it.
OpenText(): Opens an existing file and returns a StreamReaderobject.  
Open(): Opens an existing file and returns a FileStream object. We can specify the file mode and the file access type.
OpenRead(): Opens an existing file and returns a read-only FileStream object.
OpenWrite(): Opens an existing file for writing and returns a FileStream object.
Create(): Creates a new file and returns a FileStream object.
  Atomic operations:  
ReadAllBytes(): Opens a file, reads the contents of it into a byte array, and closes the file.
ReadAllLines(): Opens a file, reads the contents of it into an array of strings (one per line), and closes the file.
ReadAllText(): Opens a file, reads the contents of it into a string, and closes the file.
WriteAllBytes(): Opens a file, writes the contents of a byte array into it (overwriting any existing data), and closes the file.
WriteAllLines(): Opens a file, writes the contents of a string array into it (overwriting any existing data), and closes.
WriteAllText(): Opens a file, writes the contents of a string into it (overwriting any existing data), and closes the file.

Read Text using StreamReader

static void ReadTextStreamReader(Args _args)
{
  System.IO.StreamReader   reader;
  System.String  line;
  InteropPermissioninteropPermission;
  strtext,filepath;
  containerconfilter =['.txt','*.txt'];
  A_PurchaseOrder objA_PurchaseOrder;
  filepath = WinAPI::getOpenFileName(
    0,
    confilter,
    "",
    "Save As",
    "",
    "Untitled");
  interopPermission = newInteropPermission(InteropKind::ClrInterop);
  interopPermission.assert();
  reader = new System.IO.StreamReader(filepath,System.Text.Encoding::get_UTF7());
  line = reader.ReadLine();
  while (!System.String::IsNullOrEmpty(line))
  {
    line = reader.ReadLine();
    text  =System.Convert::ToString(line);
    info(text);
  }
  CodeAccessPermission::revertAssert();
  reader.Close();
  reader.Dispose();   
}

Write Text Using StreamReader

static void WriteFileStreamReader(Args _args)
{
  System.IO.StreamWriter     writer;
  InteropPermission interopPermission;
  strtext,filepath;
  containerconfilter =['.txt','*.txt'];
  A_PurchaseOrder objA_PurchaseOrder;
  filepath = WinAPI::getSaveFileName(
    0,
    confilter,
    "",
    "Save As",
    "",
    "Untitled");
  writer = new System.IO.StreamWriter(filepath);
  interopPermission = new InteropPermission(InteropKind::ClrInterop);
  interopPermission.assert();
  whileselectobjA_PurchaseOrder
  {
    writer.WriteLine(strFmt("%1|%2|%3|%4|%5", objA_PurchaseOrder.Purchase_ID,
      objA_PurchaseOrder.Vender_Code,
      enum2str(objA_PurchaseOrder.Status), 
      date2str(objA_PurchaseOrder.Purchase_Date,123,
            DateDay::Digits2,DateSeparator::Hyphen,
            DateMonth::Digits2,DateSeparator::Hyphen,
            DateYear::Digits4),
            objA_PurchaseOrder.Purchase_Amount));
  }
  writer.Flush();
  writer.Close();
  writer.Dispose();
  CodeAccessPermission::revertAssert();
}

Related Posts

Previous
Next Post »

1 comments:

comments
October 4, 2017 at 12:21:00 PM GMT+5:30 delete

"Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
"

Reply
avatar

Thanks for comments.....