Temp Files

In C# when you create a temp file does it have to be a text file or can you create a temp excel file?

If you can create a temp excel file, how is this done?
GoldenJagAsked:
Who is Participating?
 
AGBrownCommented:
No problem, basically I have it working with the code I've posted, repeated here in full for you. I do this:
1) Open the temp directory
2) Open an existing Excel file (in my case I use this, not a web service). I use code to do this that returns the file as a byte array, as I assume your web service is doing:
      private byte[] ReadFile()
      {
            byte[] ret = null;
            using (FileStream fs = File.OpenRead(@"C:\hello.xls")) // <--------- hello is pre-saved excel file that has hello in cell 1
            {
                  ret = new byte[fs.Length];
                  using (BinaryReader r = new BinaryReader(fs))
                  {
                        r.Read(ret, 0, (int)fs.Length);
                  }
            }
            return ret;
      }
      
3) Put my ReadFile call in place of your web service call.

4) Altered my using statement to:
      using (FileStream f = File.OpenWrite(FileName))
      {
            f.Write(test, 0, test.Length);
      }

My code then reads:
      private void button1_Click(object sender, System.EventArgs e)
      {
            string FileName = Path.GetTempFileName();
            Console.WriteLine(FileName);
            byte[] hello = this.ReadFile(); // <------------ instead of getting from the web service
            using (FileStream f = File.OpenWrite(FileName))
            {
                  f.Write(hello, 0, hello.Length);
            }
            Console.WriteLine(FileName);
      }
5) Put a breakpoint on a line _after_ the using block (in my case I put in the line Console.WriteLine(FileName);)

When I ran the code, and sat on the breakpoint, I could see the temp file in the temp directory. I copied this to disk, renamed it to temp.xls and it opened fine. I asked you to simplify it to write to C:\temp.xls just to make the debugging simpler so you don't have to search your temp directory. I would get it to work there and move it back to the temp file once you have seen that work.

Andy
0
 
GoldenJagAuthor Commented:
And can you view the temp file after it has been created?
0
 
AGBrownCommented:
You can create Excel files, but if this is a server-based program you will need some kind of plugin. I haven't used any, but there are a lot out there. There is also Office Web Components for doing spreadsheet-like things, and if you know that Excel will be on the machine you are using your program on then you can interact with Excel directly.

What is it that you are trying to do?

Andy
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
GoldenJagAuthor Commented:
I am trying to write this info from a file to an excel file.  Check out my comments (//)



 public System.Byte[] DecryptStoredFile(string[] sessionKey, int fileID) {
            object[] results = this.Invoke("DecryptStoredFile", new object[] {
                        sessionKey,
                        fileID});
            return ((System.Byte[])(results[0]));
        }



private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
{

//string strFilePath = DataGrid1.SelectedItem.Cells[2].Text;

int fileid = Convert.ToInt32(DataGrid1.SelectedItem.Cells[1].Text);
com.solu.webservices.Crypto ws = new com.solu.webservices.Crypto();

byte[] test = ws.DecryptStoredFile(pm.sessionKey,fileid);  //THE FILE INFO IS STORED HERE
                  
//WRITE The File Info TO TEMP FILE
string FileName = Path.GetTempFileName();
FileStream File_Stream = new FileStream(FileName, FileMode.Append, FileAccess.Write);
StreamWriter FileWriter = new StreamWriter(File_Stream);
try
{
                FileWriter.BaseStream.Seek(0, SeekOrigin.End);
      FileWriter.WriteLine(test);
}
:
:
finally
{
      FileWriter.Close();
}


//WRITE the info from the temp file to Detail Table via ODBC

//CALL ProcessRecords (updates files)

//DELETE TEMP FILE



0
 
vo1dCommented:
in net 1.1, you can use excel funcionality via interop and reference the com excel object in your project.
in net 2.0, you can reference the excel net wrapper to write excel files.

like andy said, the kind of file depends on what you wann do.
if you wanna write a logfile, i would prefer a simple textfile using the iostreams.

vo1d
0
 
AGBrownCommented:
OK, so you are:
1) reacting to a datagrid row click
2) getting a file from a web-service file store
3) writing that file to local disk
4) calling something that imports that into a database
5) updating the files on the web service
6) deleting the local file copy

If the web service file is an excel file, and your byte array that is returned is the decrypted file, then you should be fine writing that byte array to disk as your file contents.

So my questions now become:
1) Is the web service file an excel file?
2) Which bit of your code is not working?
0
 
GoldenJagAuthor Commented:
yes the web service file is an excel file


i dont get any errors on what i have now (the pasted snipplet) but the problem is that i cant or dont know how i can view the temp file to see if the info is correct.  i did a search but i couldnt find the file.  Also i am not sure if this line of code is how i write the web service file to the temp file:

FileWriter.WriteLine(test);
0
 
AGBrownCommented:
OK, well, as far as I can work out, your method should work fine - I don't think this will be a problem with writing excel files to disk. I would concentrate on testing the file IO code. Firstly, see if you can put a breakpoint after the FileName assignment to get the value of FileName.

Next, see if you can change your code a little to:
      ...
      //WRITE The File Info TO TEMP FILE
      string FileName = Path.GetTempFileName();
      using (FileStream f = File.Create(FileName))
      {
            f.Write(test); // <----------- Writes the byte array to disk
      }
      //WRITE the info from the temp file to Detail Table via ODBC

This will write your byte array to a new file with the name you give, and flush and close the FileStream at the end of the process

Then you can go and find the file using the value of FileName that you found.

In the meantime, I'll try and set up a test environment for what you are doing.

Andy
0
 
GoldenJagAuthor Commented:
Andy you are wonderful!!!!

I know the value of the FileName is:       FileName      @"C:\DOCUME~1\JEFFER~1\ASPNET\LOCALS~1\Temp\tmp13A3.tmp"

Again i searched for it but i cant find it.

And the contents of test look like this:  (i got it from the immed windo)

?test
{Length=13824}
    [0]: 208
    [1]: 207
    [2]: 17
    [3]: 224
    [4]: 161
    [5]: 177
    [6]: 26
    [7]: 225
    [8]: 0
   :
   :
0
 
AGBrownCommented:
Could you simplify it a little? Could you set the value of FileName to C:\temp.xls and see if can then write the spreadsheet properly?
0
 
AGBrownCommented:
By the way, that code should have read:
    f.Write(test, 0, test.Length);
0
 
GoldenJagAuthor Commented:
Andy,  when i made that last change i got two errors:

(301): Argument '1': cannot convert from 'byte[]' to 'char[]'

(301): The best overloaded method match for 'System.IO.TextWriter.WriteLine(char[], int, int)' has some invalid arguments

Any idea?
0
 
AGBrownCommented:
Hmm, could you post your latest code? Before you do, try correcting my using statement to this, and see if it makes a difference:
      using (FileStream f = File.OpenWrite(FileName))
      {
            f.Write(test, 0, test.Length);
      }
0
 
vo1dCommented:
try the Convert.ToChar(oneByte) method for each byte.
0
 
vo1dCommented:
the faster way could be writing your bytes into a memorystream and write that stream to a file.
greets, vo1d
0
 
GoldenJagAuthor Commented:
"Could you simplify it a little? Could you set the value of FileName to C:\temp.xls and see if can then write the spreadsheet properly?"

Andy i simplified the Filename and ran the code.

The contents that was in cell A1 was: System.Byte[]

This is not the info i was expecting.  i was expecting something like ssn,name,amount.

i will need a second to do the rest.
0
 
vo1dCommented:
excel files have their own structure. you will not get what you see in excel.
if you wanna write a bytearray into a file, try using :

System.IO.File.WriteAllBytes(fileName, byteArray);
0
 
GoldenJagAuthor Commented:
ok, wo1d i get the following error:

(301): 'System.IO.File' does not contain a definition for 'WriteAllBytes'
0
 
vo1dCommented:
oh, with which net version do you work? v1.1 or v2.0 ?
0
 
GoldenJagAuthor Commented:
Thanks Andy.  Give me a few minutes to see if i can get it to work.
0
 
vo1dCommented:
k, i found that the WriteAllBytes method only exists in framework 2.0.
try this to write your bytes:

using(FileStream fileStream = new FileStream(fileName, FileMode.Create))
{
   // Write the data to the file, byte by byte.
   for(int i = 0; i < dataArray.Length; i++)
   {
        fileStream.WriteByte(dataArray[i]);
   }
}
0
 
AGBrownCommented:
vo1d ... but looping through and doing individual WriteBytes is the same as doing a single Write on the fileStream, so I would think its better to drop the loop and just do the Write. I may have missed something there though?

With regard to using new FileStream(filename, ...) over File.OpenWrite(), the effect is almost inconsequential, as File.OpenWrite actually just does new FileStream underneath the hood and returns the new stream. It just acts as a simpler static facade for the same. I think use is down to personal preference.

GoldenJag; be careful with the FileMode if you specify it in "new FileStream". FileMode.Create will create a new file even if one exists. You have already created one with the Path.GetTempFileName statement, so that will reduce performance. Instead you might use FileMode.OpenOrCreate if you go down that route. However as I said, I think that File.OpenWrite is actually just a nice way of saying "new FileStream(path, FileMode.OpenOrCreate);", so I would be tempted to use the OpenWrite ... personal preference really.

A
0
 
AGBrownCommented:
Actually I'll revise that slightly, on further investigation - FileMode.Create:
"Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write and FileIOPermissionAccess.Append. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate."

So it truncates existing files. Given that you are creating an empty temporary file, it would still be better to use FileMode.Open, or FileMode.OpenOrCreate. And this still has the same effect as File.OpenWrite ;-)
0
 
vo1dCommented:
you are totally right. that example comes from msdn and not from my mind ;)
its mostly inifficent of writing each byte instead of writing four bytes in one command as an int.
i havent checked the framework yet if there is a way of writing ints instead of bytes.
if there is a method, it should be used cause its nearly 4 times faster then.

it was only a fast hint of his bytewriting problem, i did not checked for a better solution.
if your hint will not work, i will look for the int writing possibility.
greets, vo1d
0
 
GoldenJagAuthor Commented:
Works like a charm!  You are wonderful.  Thanks!!   Can you help me with the next step? i will repost the next step so you can get your points.
0
 
AGBrownCommented:
vo1d, honestly it was not criticism, just working through the problem. Fundamentally files are bytes on disk, and so the buffers used to access them would be designed around this? I would be surprised if an int write would be any improvement. I would also imagine that the Write methods of both streamwriters and the Stream objects will be optimised to write arrays of bytes in blocks rather than one at a time, but I am NOT an expert on IO. From MSDN:
"StreamWriter is designed for character output in a particular Encoding, whereas classes derived from Stream are designed for byte input and output."

GoldenJag: remind me what the next step was :-)
0
 
AGBrownCommented:
More to the point, maybe post a link to the next step here so we can find it.

A.
0
 
vo1dCommented:
i dont thought it as criticism, no problem ;)
todays systems have the possibility of writing int32 values.
the problem of writing bytes instead of a four block chunk of bytes(int) was a problem in the vc6 compiler too.
maybe ms hasent solf that problem.
if you are using java from sun, you will have the possiblity of writing ints instead of bytes.
dont know, why microsoft dont implement it.
regards, vo1d
0
 
GoldenJagAuthor Commented:
0
 
GoldenJagAuthor Commented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.