Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
i have a code to read a file ... but it shows some error ....
so what can i do....
using System;
using System.IO;
class FileRead
{
    string filereadbuf;  
    public void ReadFile(string FileName, int FileSize)
    {
        char[] buf = new char[FileSize];  
        
        StreamReader sr = new StreamReader(new FileStream(FileName, FileMode.Open, FileAccess.Read));
        int retval = sr.ReadBlock(buf, 0, FileSize); // 
        Console.Write("Total Bytes Read = " + retval + "\n");
        filereadbuf = new string(buf);  
        Console.WriteLine(filereadbuf); 
        sr.Close();
    }
}
 
class TestFileRead
{
    public static void Main(string[] args)
    {
        String[] cmdline = Environment.GetCommandLineArgs(); 
        Console.WriteLine("File Reader Using Stream Reader & File Stream \n");
        if (cmdline.Length < 2) 
        {
            Console.WriteLine("Usage: " + cmdline[0] + " <input file> ");
            return;
        }
      
      
        File[] fe = (new Directory(".")).GetFiles(cmdline[1]);
        if (fe.Length == 0)
        {
            Console.WriteLine(cmdline[1] + ": file not found"); 
            return;
        }
        FileRead fr = new FileRead();
        try
        {
            fr.ReadFile(cmdline[1], (int)fe[0].Length); 
        }
        catch (IOException e)
        {
            Console.WriteLine("I/O error occured" + e);
            return;
        }
    } 
}
Posted 17-Jan-13 22:57pm
Edited 17-Jan-13 22:58pm
v2
Comments
Mohd. Mukhtar at 18-Jan-13 5:00am
   
What error are you getting?
prajwal rao at 18-Jan-13 5:04am
   
Error 1 'System.IO.File': array elements cannot be of static type Error 2 Cannot declare a variable of static type 'System.IO.File[] Error 3 Cannot create an instance of the static class 'System.IO.Directory Error 4 'System.IO.File' does not contain a definition for 'Length' and no extension method 'Length' accepting a first argument of type 'System.IO.File' could be found (are you missing a using directive or an assembly reference?
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

There are quite a few things you need to look at here, but the compilation error you are probably getting relates to the line:
        File[] fe = (new Directory(".")).GetFiles(cmdline[1]);
And tells you that you can't create an array of static objects.
 
The problem is that the File class is static - there is one and only one instance of it for the entire application, so you cannot under any circumstances create a File variable, and certainly not an array of them - because you can't get at the object to fill it with!
 
Butthere is a wider problem with this line: GetFiles is a static property of the Directory class, and it doesn't return File objects, it returns an array of strings. So what you actually should have said here is:
            string[] fe = Directory.GetFiles(cmdline[1]);
But that isn't actually what you want to do either! There is a much, much easier way to achieve what you want:
if (!File.Exists(cmdline[1]))
    {
    Console.WriteLine(cmdline[1] + ": file not found");
    return;
    }
 

"sir can u edit the above code and update it please using if(!File.Exists(loadFille)"
 
Well...it's your homework...so I really shouldn't...
 
But, ok - if you can tell me exactly what is going on, and why I moved some of your code around!
            public static void Main(string[] args)
                {
                String[] cmdline = Environment.GetCommandLineArgs();
                Console.WriteLine("File Reader Using Stream Reader & File Stream \n");
                if (cmdline.Length < 2)
                    {
                    Console.WriteLine("Usage: " + cmdline[0] + " <input file> ");
                    return;
                    }
                string loadFile = cmdline[1];
 
                if (!File.Exists(loadFile))
                    {
                    Console.WriteLine(loadFile + " : file not found");
                    return;
                    }
                try
                    {
                    FileRead fr = new FileRead();
                    FileInfo fi = new FileInfo(loadFile);
                    fr.ReadFile(loadFile, (int) fi.Length);
                    }
                catch (IOException e)
                    {
                    Console.WriteLine("I/O error occured" + e);
                    return;
                    }
                }
  Permalink  
v2
Comments
prajwal rao at 18-Jan-13 5:20am
   
but where to put this code sir... if (!File.Exists(cmdline[1])) { Console.WriteLine(cmdline[1] + ": file not found"); return; }
OriginalGriff at 18-Jan-13 5:25am
   
In place of the existing (bad) code: File[] fe = (new Directory(".")).GetFiles(cmdline[1]); if (fe.Length == 0) { Console.WriteLine(cmdline[1] + ": file not found"); return; }
prajwal rao at 18-Jan-13 5:27am
   
ok now i got 1 new error Error 1 The name 'fe' does not exist in the current context
OriginalGriff at 18-Jan-13 5:44am
   
That is because you are now trying to use the number of elements in a array (that you couldn't declare) as the number of bytes you should read from a file... I would suggest you look at creating a FileInfo instance... FileInfo fi = new FileInfo(path); long numberOfBytesInTheFile = fi.Length; Can you guess what you should use instead of the "path" parameter? :laugh:
prajwal rao at 18-Jan-13 5:53am
   
sorry sir.... i am new for this language.... just learning.....:( i cant guess it...:(
OriginalGriff at 18-Jan-13 5:59am
   
Yes you can! :laugh: Think about it: where is the name of the file you want to open?
prajwal rao at 18-Jan-13 6:07am
   
oh ya.....sh*t....:( where i have to specify that sir...???
OriginalGriff at 18-Jan-13 6:14am
   
Instead of the word "path". Personally, I would create a string variable called "path", or more likely "loadFile" and set the content of the argument into it to start with. Then I would use "loadFile" instead of "cmdline[1]" throughout. It makes the code a lot more readable if you are looking at: if (!File.Exists(loadFile) instead of if (!File.Exists(cmdline[1])) and so forth - which makes it easier to get it right! :) (Think about it - you don't have to think about parameters, but about files. So if you change it later to get a file name from the user when he types it in, you have to change less of your code - which makes it more reliable)
prajwal rao at 18-Jan-13 6:20am
   
sir can u edit the above code and update it please using if(!File.Exists(loadFille)
OriginalGriff at 18-Jan-13 6:31am
   
Answer updated
prajwal rao at 18-Jan-13 6:40am
   
sir its not my homework... just am learning c# myself.....
OriginalGriff at 18-Jan-13 6:47am
   
I hope you are using a book or similar - "pick it up as you go" is a very bad idea with something as big as .NET. You can miss so much stuff which makes your life easier. For example: string content = File.ReadAllText(loadFile) does in one line what your code does in quite a few!
prajwal rao at 18-Jan-13 6:53am
   
ya sir am using book to learn.... is there any different code to read a file other then the above code....???
OriginalGriff at 18-Jan-13 7:07am
   
Loads! There are a whole bunch of File methods (ReadAllLines, ReadAllBytes, and others), there are the Stream methods, the derived streams, and buch of specialised ones - see what I mean by so much stuff? Have a look at the File class in MSDN - it is the simplest interface to files, but is very powerful.
prajwal rao at 18-Jan-13 7:11am
   
hmmmm ya i have visited it now sir...... can you give me a simplest method to read a file..... very short code.....
OriginalGriff at 18-Jan-13 7:51am
   
I already did: string content = File.ReadAllText(loadFile);
prajwal rao at 18-Jan-13 8:15am
   
how about this code using System; using System.IO; using System.Text; class Test { public static void Main() { string path = @"E:\\new.txt"; using (FileStream fs = File.OpenRead(path)) { byte[] b = new byte[4096]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b, 0, b.Length) > 0) { Console.WriteLine(temp.GetString(b)); } } }
OriginalGriff at 18-Jan-13 8:21am
   
That should work, but it'll probably be a bit slow - you are retrieving each byte individually, and converting it to a string, which is not necessarily the best way. You might find it quicker to fetch all the bytes at once using File.ReadAllBytes, and then UTF convert the lot. Plus, if you have a big file, the WriteLines are going to take quite a while! :laugh: It depends what you are trying to do and why - if you are trying to learn about streams, then try the exercises in your book: they should expand on the material covered in the chapter in a logical progression.
prajwal rao at 18-Jan-13 8:24am
   
well thank you sir..... am trying to read only 4096 bytes data
Orcun Iyigun at 18-Jan-13 9:03am
   
If that worked for you mark his solution as an ANSWER!!!
OriginalGriff at 18-Jan-13 9:24am
   
I understand - but you shouldn't assume you will use the same code for just that. If you expand the use in two weeks time to read 1MB files, you might wish you had written it to run a bit quicker! :laugh:
BC @ CV at 18-Jan-13 9:49am
   
You are a very patient guy. +5
OriginalGriff at 18-Jan-13 10:25am
   
Not really! :laugh: But sometimes beginners need a little more time and effort...
Andreas Gieriet at 18-Jan-13 8:30am
   
You run into the same wall as I did in the previous thread. He does not read your answers nor does he follow your advise not does he rasonably answer to questions. I'm clue-less. I mean he asks for the simplest file reading C# code, and when you provide, he does not follow up, but jumps to something else. Weird. Andi
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

  Permalink  
Comments
prajwal rao at 18-Jan-13 5:28am
   
ok thank you....
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Brute force approach(requires LINQ):
public static string ReadHeader(string filePath, int maxLen)
{
    return new string(File.ReadAllText(filePath).Take(maxLen).ToArray());
}
By using StreamReader class:
public static string ReadHeader(string filePath, int maxLen)
{
    using (var reader = new StreamReader(filePath))
    {
        int pos = 0;
        char[] buffer = new char[maxLen];
        int n = reader.ReadBlock(buffer, pos, maxLen) - pos;
        return new string(buffer, 0, n);
    }
}
Cheers
Andi
  Permalink  

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 412
1 sanket saxena 355
2 Abhinav S 258
3 OriginalGriff 235
4 CPallini 205
0 Sergey Alexandrovich Kryukov 8,704
1 OriginalGriff 5,000
2 Peter Leow 3,839
3 Maciej Los 3,535
4 Er. Puneet Goel 3,107


Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 18 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid