Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Temp Files

Posted on 2006-04-13
30
Medium Priority
?
753 Views
Last Modified: 2008-03-10
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?
0
Comment
Question by:GoldenJag
  • 11
  • 11
  • 8
30 Comments
 

Author Comment

by:GoldenJag
ID: 16446459
And can you view the temp file after it has been created?
0
 
LVL 12

Expert Comment

by:AGBrown
ID: 16446469
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
 

Author Comment

by:GoldenJag
ID: 16446579
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 11

Expert Comment

by:vo1d
ID: 16446599
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16446655
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
 

Author Comment

by:GoldenJag
ID: 16446692
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16446803
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
 

Author Comment

by:GoldenJag
ID: 16446884
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16446905
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16446924
By the way, that code should have read:
    f.Write(test, 0, test.Length);
0
 

Author Comment

by:GoldenJag
ID: 16446951
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16446978
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
 
LVL 11

Expert Comment

by:vo1d
ID: 16446982
try the Convert.ToChar(oneByte) method for each byte.
0
 
LVL 11

Expert Comment

by:vo1d
ID: 16447007
the faster way could be writing your bytes into a memorystream and write that stream to a file.
greets, vo1d
0
 

Author Comment

by:GoldenJag
ID: 16447043
"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
 
LVL 11

Expert Comment

by:vo1d
ID: 16447071
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
 

Author Comment

by:GoldenJag
ID: 16447103
ok, wo1d i get the following error:

(301): 'System.IO.File' does not contain a definition for 'WriteAllBytes'
0
 
LVL 12

Accepted Solution

by:
AGBrown earned 2000 total points
ID: 16447116
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
 
LVL 11

Expert Comment

by:vo1d
ID: 16447125
oh, with which net version do you work? v1.1 or v2.0 ?
0
 

Author Comment

by:GoldenJag
ID: 16447139
Thanks Andy.  Give me a few minutes to see if i can get it to work.
0
 
LVL 11

Expert Comment

by:vo1d
ID: 16447333
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16447429
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16447507
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
 
LVL 11

Expert Comment

by:vo1d
ID: 16447548
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
 

Author Comment

by:GoldenJag
ID: 16447553
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16447605
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
 
LVL 12

Expert Comment

by:AGBrown
ID: 16447623
More to the point, maybe post a link to the next step here so we can find it.

A.
0
 
LVL 11

Expert Comment

by:vo1d
ID: 16447670
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

810 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