Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
These question(s) that I'm asking are easy pickins for the up and becoming wizards. Yet, I cannot find the answers to them. Basically, I trying to find the following information on files, such as: In C#.

Of course, the file does exist...
1) What is the file's record count ( number of records contained therein ).
2) Does this file contains fixed length records or variable length records.
A) If the file contains fixed length records:
what is the overall record length? ##
B) Throw an indication thereof, to indicate fixed length feature.

I have already found the File size, using a FileInfo.Length feature. OR is there a
better method in getting this information. I've noticed, using this
FileInfo.Length feature, that it seems to increase each time I ran a program
calling for this information; and while I was writing these questions.

What's the real function differences between C#'s "File." and C#'s "FileInfo." ? Are
they basically the same or what. Are there others; others that are they better and
provides more functions? Some real solid working c# examples sure would be nice to
back up your point of view and experience.

Can C# implement a truely random access file system in its fullest??; Like in
fortran 77 or in COBOL( that I used a long time ago? e.g.: an ISAM method);
with no needed intermediate steps involved.

And again thanks,

Member 15028314

What I have tried:

The usual fully tested trial and error method, which usually works in the long run.
Posted
Updated 19-Apr-21 18:16pm
v4
Comments
[no name] 19-Apr-21 1:02am    
Record lengths (fixed; variable) require knowing the format of the file; or being able to figure it out from the contents. If the file is encrypted, probably none.
Member 15028314 19-Apr-21 1:44am    
Sorry Gerry, you speculating.
Rick York 19-Apr-21 11:34am    
No, he isn't. Those are FACTS that someone who has written code to read a lot of files has learned. Having done so myself, I agree with him fully and those are fairly obvious things you need to know. If you read solution 1 you will see essentially the same things being stated.

These are not speculations by anyone. They are prerequisites to implementing what you are asking. Until you know or define those things you will not get very far.

One other thing - COBOL and F77 do not actually implement the file systems. The operating system does and the languages provide libraries to interface with them.
Member 15028314 19-Apr-21 19:12pm    
Ok Gerry and Rick: I'm of the old college, I have also written many fortran 77 programs implimenting and using random access files on a DEC vax/vms 11780 at school and professional work. I also written cobol programs using an ISAM methods also. Hum?

1) What is the file's record count :
    --> Since we do not know anything about the file, how could we answer that?
2) Does this file contains fixed length records or variable length records. :
    --> Again, how could we tell?
A) If the file contains fixed length records:
what is the overall record length? ## :
    --> see answer 2
B) Throw an indication thereof, to indicate fixed length feature. :
    --> N/A

FileInfo.Length feature, that it seems to increase each time I ran a program
calling for this information; and while I was writing these questions.
    --> Without detailed evidence we cannot comment.
        You could use the FileStream.Seek() method, but FileInfo is probably the better choice.

Can C# implement a truely random access file system in its fullest?
    --> Yes, just as code written in any language can.
 
Share this answer
 
What is the file's record length, fixed or variable length records?
The concept of records does not apply. The file a series of 1s and 0s organized into eight bits called a byte. You determine how the bytes relate to each other as a "record".
Each byte in the file may be addressed randomly.
To further complicate things, even characters may have different representations. There are single byte character set, double byte character sets and quad bytes character sets. Code page sets map characters to numeric values. There are many standard code page sets.
The way a line of text ends varies by operating system.
Windows usesCR carriage return and line feed as a line ending ("\r\n", \r is 0x0D in hexadecimal, 13 in decimal and Line Feed \n is 0x0A in hexadecimal, 10 in decimal)

Linux uses only a Line feed (0x0A in hexadecimal, 10 in decimal) for a line ending


File versus FileInfo
The File class is static and does not need a constructor. I typically use it to determine if a file exists but you need to be cautious when checking for existence.
if(!File.Exists("C:\Zones.Txt")) 
  do something<\pre>
will throw an exception if you are not authorized to access the file.


  The FileInfo class requires a constructor but subsequent requests (file access times and file attributes) are very fast as the information is obtained from the in memory class. Place the FileInfo constructor in a try/catch to avoid exceptions.
<pre>FileInfo fileInfo = null;
try(fileInfo = new FileInfo("C:\Zones.Txt")) 
catch (Exception ex)
{ Console.WriteLine(ex.Message); }


The following program creates files using various character sets. You can see the CR/LF and the number of bytes used by each character. After the demonstration files are created, view the contents of the files using Notepad. Windows will recognize the various encoding techniques and correctly display the lines.
<pre>using System;
using System.Globalization;
using System.IO;
using System.Text;

namespace EncodingDemo
{
  class Program
  {
    private static string[] _lines = new string[]
      {"Line 01", "Line 02", "Line 03"};

    private static string _outputPath = "";

    private static void Main(string[] args)
    {
      Console.WriteLine("EncodingDemo - Text formats");

      Console.WriteLine("Please provide an output path (for example I:/TextDemo");
      string documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      Console.WriteLine("Default is: " + documentsFolder);
      string outputPath = Console.ReadLine();
      if (String.IsNullOrEmpty(outputPath))
        _outputPath = documentsFolder;
      else
        _outputPath = outputPath;

      //create and display text files with various encodings
      CreateFile("TextDemo-" + "ASCII", Encoding.ASCII);
      CreateFile("TextDemo-" + "UTF8", Encoding.UTF8);
      CreateFile("TextDemo-" + "Unicode", Encoding.Unicode);
      CreateFile("TextDemo-" + "UTF32", Encoding.UTF32);
      CreateStringText("TextDemo-" + "Strings");

      Console.WriteLine("");
      Console.WriteLine("Press any key to terminate this program");
      Console.ReadKey();
    }

    /// <summary>
    /// Create a file with the desired encoding. The input text is stored in _lines.
    /// </summary>
    /// <param name="outputFileName">name of the file to be created</param>
    /// <param name="encoding">encoding to use</param>
    private static void CreateFile(string outputFileName, Encoding encoding)
    {
      string fileName = Path.Combine(_outputPath, outputFileName + ".txt");
      Console.WriteLine("");
      Console.WriteLine("Creating " + fileName);
      try
      {
        using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
        using (StreamWriter streamWriter = new StreamWriter(fileStream, encoding))
        {
          foreach (string line in _lines)
            streamWriter.WriteLine(line);
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine("Error on file: " + fileName);
        Console.WriteLine("  " + ex.Message);
        return;
      }

      FileInfo fileInfo = new FileInfo(fileName);
      if (fileInfo.Exists)
      {
        Console.WriteLine("  File length: " + fileInfo.Length.ToString("n0", CultureInfo.CurrentCulture));
        ShowHex(fileName);
      }
      else
        Console.WriteLine("File not found");
    }

    private static void CreateStringText(string outputFileName)
    {
      string fileName = Path.Combine(_outputPath, outputFileName + ".txt");
      Console.WriteLine("");
      Console.WriteLine("Creating " + fileName);
      using (StreamWriter streamWriter = new StreamWriter(fileName))
      {
        streamWriter.Write(_lines[0]);
        streamWriter.WriteLine(_lines[1]);
        streamWriter.Write(_lines[2]);
      }

      FileInfo fileInfo = new FileInfo(fileName);
      if (fileInfo.Exists)
      {
        Console.WriteLine("  File length: " + fileInfo.Length.ToString("n0", CultureInfo.CurrentCulture));
        ShowHex(fileName);
      }
      else
        Console.WriteLine("File not found");
    }


    private static void ShowHex(string fileName)
    {
      Console.WriteLine("Offset             Hex values");
      FileStream fileStream = null;     //base
      BinaryReader fileReader = null;   //reader
      fileStream = File.OpenRead(fileName);
      using (fileReader = new BinaryReader(fileStream))
      {
        StringBuilder sb = new StringBuilder();
        sb.Append(ToHex(fileStream.Position));
        sb.Append("  ");
        int
          counter = 0,
          groupSets = 0;
        while (fileStream.Position < fileStream.Length)
        {
          byte singleByte = fileReader.ReadByte();
          sb.Append(ToHex(singleByte));
          if (++counter >= 4)
          { //convert to hex and set up for display
            sb.Append(" ");       //pad between group sets
            if(++groupSets >= 8)  //maximum group sets per line
            { //display a lines of hex values
              Console.WriteLine(sb.ToString());
              sb.Clear();
              sb.Append(ToHex(fileStream.Position)); //show the new position of fileStream
              sb.Append("  "); 
              groupSets = 0;
            }
            counter = 0;
          }
        }
        Console.WriteLine(sb.ToString());
      }
    }

    /// <summary>
    /// Covert a byte to hex digits with leading zeros as needed
    /// </summary>
    /// <param name="byteValue"></param>
    /// <returns>right justified, zero filled hex byte value</returns>
    private static string ToHex(byte byteValue)
    {
      string strHex = String.Format("{0:X0}", byteValue);
      string rslt = "0000" + strHex;
      strHex = rslt.Substring(rslt.Length - 2);
      return strHex;
    }

    /// <summary>
    /// Convert a long to display hex
    /// </summary>
    /// <param name="integer32">number to be converted</param>
    /// <returns>right justified, zero filled UInt32 in hex</returns>
    private static string ToHex(UInt32 integer32)
    {
      string strHex = String.Format("{0:X0}", integer32);
      string rslt = "00000000" + strHex;
      strHex = rslt.Substring(rslt.Length - 8);
      return strHex;
    }

    /// <summary>
    /// Convert a long to display hex
    /// </summary>
    /// <param name="longInt">number to be converted</param>
    /// <returns>right justified, zero filled Int64 in hex</returns>
    private static string ToHex(Int64 longInt)
    {
      UInt32 upper32 = (UInt32)(longInt >> 32);
      UInt32 lower32 = (UInt32)(longInt & 0x00000000ffffffff);
      return ToHex(upper32) + " " + ToHex(lower32);
    }
  }
}


I hope this helps to clarify the structure of a file.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900