Solved

Write a string to a file

Posted on 2004-08-18
2
250 Views
Last Modified: 2010-04-15
Hello,
I have strings of different length to be written to a flat file. The block to be written to file (containing single string) must contain 255 characters. (in order to write in a kind of a structure to a file). Is there a function to write such blocks WITHOUT having to "fill up" every string to 255-character size? If not, what could be the fastest solution?
Thx in advance!
0
Comment
Question by:zaratin
2 Comments
 
LVL 10

Accepted Solution

by:
eternal_21 earned 125 total points
ID: 11834348
Assuming you are saving using a FileStream, the following method would work (truncates strings longer than 255 characters):

  static void WriteString(System.IO.FileStream fileStream, string outString)
  {
    byte[] textBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(outString);
    byte[] bytes = new byte[(textBytes.Length > 255 ? (int)textBytes.Length : 255)];
    textBytes.CopyTo(bytes, 0);
    fileStream.Write(bytes, 0, 255);
  }

(throws exception if string is longer than 255 characters)

  static void WriteString(System.IO.FileStream fileStream, string outString)
  {
    byte[] bytes = new byte[255];
    System.Text.ASCIIEncoding.ASCII.GetBytes(outString).CopyTo(bytes, 0);
    fileStream.Write(bytes, 0, 255);
  }
0
 

Author Comment

by:zaratin
ID: 11853782
Thx, eternal_21. Very nice solution...
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question