Results 1 to 22 of 22

Thread: How do I create a file in memory as opposed to one on HDD

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22

    Question How do I create a file in memory as opposed to one on HDD


    Is it possible to create a file in memory instead of on HDD. If yes, then how?

    I want to avoid creating a temporary file on the HDD for security reasons.


  2. #2
    Fanatic Member pax's Avatar
    Join Date
    Mar 2001
    Location
    Denmark
    Posts
    840
    Hi.

    Instead of writing your data to a filestream you could use a memorystream.
    I wish I could think of something witty to put in my sig...

    ...Currently using VS2013...

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22
    I am trying to read a binary (bitmap) data from database (a separate thread). On retrieval the data is returned as string whereas I need it as byte() which I then route through memorystream to a bitmap. But it doesn't quite work as getchunk returns a string!

    The workaround would be to create a HDD file from getChunk and do a image.FromFile, and that's why the question (to avoid a HDD file).

    So, if a memorystream can simulate this, it would be nice. But from what little I know about memorystream, it can be filled using byte() (back to where I started).

  4. #4
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    The simple answer would be to not use GetChunk then. Maybe this will help:

    http://www.edneeis.com/tutorial.aspx?ID=7

  5. #5

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22

    Question

    Thanks for the help.

    Problem is: I don't know how to connect to Access database using SQLClient. I've all along used ADODB. I've tried the example with OleDb but still same casting error.

    In the code you've linked to, I presume that DataRow passed to ExportImageFromDB is coming from a Dataset.

  6. #6
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Yes the datarow would be for a dataset and the overloaded version handles the datareader. To switch it to Oledb just replace any reference to Sql components with Oledb and/or add an imports System.Data.Oledb. So SqlDataReader would be OledbDataReader with the imports at the top.

  7. #7

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22

    Question

    I still get the error: "Specified cast in not valid"!!!

    Is it something in setup of my vb.net? I am using vb.net 2003 (not the studio) on XP Pro.

    VB Code:
    1. Option Strict Off
    2. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    3.         Dim conn As OleDb.OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\TEMP\DB1.MDB")
    4.         conn.Open()
    5.         Dim cmd As New OleDb.OleDbCommand("SELECT * FROM BMP", conn)
    6.         Dim da As New OleDb.OleDbDataAdapter(cmd)
    7.         Dim cb As New OleDb.OleDbCommandBuilder(da)
    8.         Dim ds As New DataSet
    9.         Dim dr As DataRow
    10.  
    11.         Dim odr As OleDb.OleDbDataReader
    12.         odr = cmd.ExecuteReader
    13.         odr.Read()
    14.         MsgBox(odr.Item("LEN_BMP"))
    15.         Dim mydata() As Byte
    16.         Try
    17.             mydata = CType(odr.Item("BMP"), Byte())
    18.         Catch ex As Exception
    19.             MsgBox(ex.Message)
    20.         End Try
    21. End Sub

  8. #8
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    When you get an exception you should check it's stacktrace property for more information (like the line number that is causing the ruckus). These lines are not needed:
    Dim da As New OleDb.OleDbDataAdapter(cmd)
    Dim cb As New OleDb.OleDbCommandBuilder(da)
    Dim ds As New DataSet
    Dim dr As DataRow

    VB Code:
    1. Option Strict Off
    2. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    3.         Dim conn As OleDb.OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\TEMP\DB1.MDB")
    4.         conn.Open()
    5.         Dim cmd As New OleDb.OleDbCommand("SELECT * FROM BMP", conn)
    6.         Dim odr As OleDb.OleDbDataReader = cmd.ExecuteReader
    7.         If odr.Read() Then
    8.              MsgBox(odr.Item("LEN_BMP"))
    9.              Dim mydata() As Byte
    10.              Try
    11.             'if the next line is where it bombs then you don't have an array of bytes stored in the database
    12.                    mydata= odr.Item("BMP")
    13.               Catch ex As Exception
    14.             MsgBox(ex.StackTrace,,ex.Message)
    15.               End Try
    16.         End If
    17. End Sub

  9. #9

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22

    Lightbulb


    Someone said, either in this thread or a related thread, that if I am getting "Specified cast is not valid (or something like that)", may be the data being retrieved is not binary. Should've listened. Also don't believe when it says memo field can be used for storing images.

    So a hundred dollars (for buying books) poorer and after a weekend with out any sleep, I realized that field BMP in table was defned as MEMO. I changed it to OLE Object, and <poof> the error is gone. Not only that, in the debugger/step mode, I can see that the data that comes back is ok.

    Well, I chalk up my mistakes to experience, but your mistakes, a different story.

    Here's the code.
    Button1 inserts a row in empty BMP table, Button2 retrieves it.

    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.     Dim ssql As String
    3.     Dim sConn As String
    4.     Dim objDA As OleDbDataAdapter
    5.     Dim objDS As New System.Data.DataSet
    6.     Dim objRow As Data.DataRow
    7.     Dim objDt As Data.DataTable
    8.     Dim objcb As OleDbCommandBuilder
    9.  
    10.     sConn = "Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\TEMP\DB1.MDB"
    11.     ssql = "SELECT * FROM bmp"
    12.     objDA = New OleDbDataAdapter(ssql, sConn)
    13.     objcb = New OleDbCommandBuilder(objDA)
    14.     objDA.Fill(objDS, "BMP")
    15.     objDt = objDS.Tables("BMP")
    16.     objRow = objDt.NewRow()
    17.     Dim b() As Byte = {96, 97, 98}
    18.     objRow("BMP") = b
    19.     objRow("LEN_BMP") = 3
    20.     objDS.Tables("BMP").Rows.Add(objRow)
    21.  
    22.     objDA.Update(objDS, "BMP")
    23. End Sub
    24.  
    25. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    26.     Dim ssql As String
    27.     Dim sConn As String
    28.     Dim objDA As OleDbDataAdapter
    29.     Dim objDS As New System.Data.DataSet
    30.     Dim objRow As Data.DataRow
    31.     Dim objDt As Data.DataTable
    32.     Dim objcb As OleDbCommandBuilder
    33.     sConn = "Provider=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=C:\TEMP\DB1.MDB"
    34.     ssql = "SELECT * FROM bmp"
    35.     objDA = New OleDbDataAdapter(ssql, sConn)
    36.     objcb = New OleDbCommandBuilder(objDA)
    37.     objDA.Fill(objDS, "BMP")
    38.     objDt = objDS.Tables("BMP")
    39.     objRow = objDt.Rows(0)
    40.     Dim b() As Byte
    41.     b = objRow("BMP")
    42. End Sub

    That concludes our thread. Thanks for joining us and contributing. Have a nice day.
    (On your way out, you can contribute to a good cause; Sending me on a vacation.)

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22

    Reopned

    I've reopened the thread as the actual subject never got addressed i.e. how to create files in memory without going to HDD!!!

  11. #11
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    I don't understand now, because you have the image in your byte array , b, in the above code.

    Let's pretend that you were saving it to a hdd after you pulled it out of the database, what did you plan on doing with it?

  12. #12

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22
    This is what I intend on doing:

    Create a bitmap in memory based on certain data.
    Display it to user. Once approved by user save it in database.
    At a future date, when the need arises, retrieve the image from the database and display it on the monitor or print it.

    Since the bitmap may contain sensitive data, I don't want to put it in a file on the HDD. I know, there is always a possibility that paging file may contain such data and some one can actually break into database...but still.

  13. #13
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    Why not just encrypt the image and save it wherever?

    A web app I'm developing does just that... and there's no way unless you know the encryption key (store it in the database, encrypted itself in the registry, or wherever). We save the image on the webserver, and since they are encrypted, there is no way for webmasters to peruse sensitive images.
    Last edited by nemaroller; Apr 7th, 2004 at 06:33 PM.

  14. #14
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    Here's a sample (not that it automatically works for your setup) which takes a string which is actually a GUID, that the database assigns to new records of the images, and then uses that as the filename for the image on the server.

    The code you don't see in this function, creates a Guid for the filename, stores that plus the file's extension, and original filename in the Sql server.


    VB Code:
    1. Private Function uploaddata(ByVal newmediaguidname As String) As Boolean
    2.  
    3.         'Variable to hold the FileName
    4.         Dim m_strFileName As String
    5.         'Variable FolderName where the files  will be saved
    6.         Dim m_strFolderName As String = Server.MapPath("/yourwebserver") & "/Data/"
    7.         'Variable to hold the File
    8.         Dim m_objFile As HttpPostedFile
    9.         'Variable used in the Loop
    10.         Dim i As Integer
    11.  
    12.         Try
    13.             'Get the HttpPostedFile
    14.             m_objFile = Request.Files(0)
    15.             'Check that the File exists, has a name, and is not empty
    16.             If Not (m_objFile Is Nothing Or m_objFile.FileName = "" Or m_objFile.ContentLength < 1) Then
    17.  
    18.                 'Creates the containing folder on the server if it does not exist
    19.                 If (Not Directory.Exists(m_strFolderName)) Then
    20.                     Directory.CreateDirectory(m_strFolderName)
    21.                 End If
    22.  
    23.                 'encrypt the stream
    24.                 Dim UE As New UnicodeEncoding
    25.                 Dim des As New RijndaelManaged '<-this is a System.Net class, don't freak out
    26.                 Dim key As Byte()
    27.  
    28.                 [b]key = UE.GetBytes("aUniqueKeyGoesHere") 'change the string to something unique[/b]
    29.                 Dim myicryptotransform As ICryptoTransform = des.CreateEncryptor(key, key)
    30.                 Dim fileData(m_objFile.InputStream.Length) As Byte
    31.                 m_objFile.InputStream.Read(fileData, 0, m_objFile.InputStream.Length)
    32.                 Dim fs As FileStream = New FileStream(m_strFolderName & newmediaguidname & ".kjb", FileMode.CreateNew) 'i used .kjb, use any made up extension you wish
    33.                 Dim mycryptostream As New CryptoStream(fs, myicryptotransform, CryptoStreamMode.Write)
    34.                 mycryptostream.Write(fileData, 0, fileData.Length)
    35.                 mycryptostream.Close()
    36.                 fs.close()
    37.  
    38.              
    39.  
    40.             Else
    41.                 Return False
    42.             End If
    43.  
    44.         Catch errorVariable As Exception
    45.             'Trap the exception
    46.             Return False
    47.         End Try
    48.         Return True
    49.  
    50.     End Function
    Last edited by nemaroller; Apr 7th, 2004 at 06:37 PM.

  15. #15

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22
    nemaroller:

    Are you sure the above example is for creating a file in the memory? Appears more like how to get file from a webserver.

  16. #16
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    Ok, I posted that code because it shows how easy it is to just encrypt the images on the web server, where they would most likely be stored, instead of putting them in a database. The code actually encrypts a file submitted to a website, and stores it in the website folder.

    If you want to store the image as a string in a database, all you have to do is write the Cryptostream to a streamwriter, which in turns writes to a StringBuilder, and then use StringBuilders' ToString method to grab the string to store in the database.

    It be almost identical to my example above, except my examples writes the image to a filestream.

    Off the track:
    IF you use Image.FromStream , once that is executed, you have the image in MEMORY. What you decide to do with it from there is your choice.
    Last edited by nemaroller; Apr 9th, 2004 at 01:15 PM.

  17. #17
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    It seems to me all you need to do is encrypt the image, so other users CANNOT just open them up and look at them.

    You can store the image in a public folder, on a public web server, or in a database. Either way, they should be encrypted.

    The best place to store the image really depends on what your project is, and what you need to accomplish. YOu haven't given us any other details, so I don't know which way to direct you to.

    Unless its absolutely necessary, because images are usually large, I would stay away from storing images in databases.

  18. #18

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22
    I am writing a signature capture program for Credit card processing and don't fill comfortable about storing such data in files on HDD and hence the database route. Also it is easier for me to find the signature when in database.

  19. #19
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    VB Code:
    1. 'get an imaginary image
    2.         'i use a hard drive image to simulate your 'capture'
    3.  
    4.         Dim myinputstream As New IO.FileStream("C:\Documents and Settings\Karl\My Documents\My Pictures\babybeyer.jpg", IO.FileMode.Open)
    5.         Dim myimg As Image = Image.FromStream(myinputstream)
    6.         myinputstream.Close()
    7.  
    8.  
    9.         'create a graphics object for the image
    10.         Dim mybmp As New Bitmap(myimg)
    11.         'now we destroy the image source
    12.         myimg.Dispose()
    13.  
    14.         'we will now save it to memory
    15.         Dim mymemorystream As New IO.MemoryStream
    16.         mybmp.Save(mymemorystream, Imaging.ImageFormat.Jpeg)
    17.  
    18.         'we destroyed the image
    19.         mybmp.Dispose()
    20.         'we will now populate the picturebox to prove the image
    21.         'came from memory
    22.  
    23.         PictureBox1.Image = Image.FromStream(mymemorystream)
    24.         mymemorystream.Close()

  20. #20
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    And here's a more complete example, which is probably what you really want, as it shows how to store the image to a string, or a byte array, so you can save that to the database.

    NOTE: you'll need two pictureboxes
    VB Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.  
    3.  
    4.         'get an imaginary image
    5.         'i use a hard drive image to simulate your 'capture'
    6.  
    7.         Dim myinputstream As New System.IO.FileStream("C:\test.jpg", IO.FileMode.Open)
    8.         Dim myimg As Image = Image.FromStream(myinputstream)
    9.         myinputstream.Close()
    10.  
    11.  
    12.         'create a graphics object for the image
    13.         Dim mybmp As New Bitmap(myimg)
    14.         'now we destroy the image source
    15.         myimg.Dispose()
    16.  
    17.         'we will now save it to memory
    18.         Dim mymemorystream As New System.IO.MemoryStream
    19.         mybmp.Save(mymemorystream, System.Drawing.Imaging.ImageFormat.Jpeg)
    20.  
    21.         'we destroyed the image
    22.         mybmp.Dispose()
    23.         'we will now populate the picturebox to prove the image
    24.         'came from memory
    25.  
    26.      'put image from memory into picturebox
    27.         PictureBox1.Image = Image.FromStream(mymemorystream)
    28.  
    29.         'now, also store the binary data into a bytearray
    30.         mymemorystream.Seek(0, System.IO.SeekOrigin.Begin)
    31.         Dim mybytearray(mymemorystream.Length) As Byte
    32.         mymemorystream.Read(mybytearray, 0, mymemorystream.Length)
    33.         mymemorystream.Close()
    34.  
    35.  
    36.         'convert the bytearray contents to string
    37.         Dim myencoding As System.Text.UnicodeEncoding = New System.Text.UnicodeEncoding
    38.         Dim myStringData As String = myencoding.GetString(mybytearray)
    39.  
    40.         'image is now held within a STRING
    41.         '( put string in databse)
    42.  
    43.      '(retrieve string from database)
    44.         'now convert the string back into a byte array to prove the image persists
    45.         'in the string
    46.  
    47.         Dim mydecoding = New System.Text.UnicodeEncoding
    48.         mybytearray = mydecoding.GetBytes(myStringData)
    49.  
    50.         'now retrieve the data from the byte array, and stick it into the image
    51.         mymemorystream = New System.IO.MemoryStream(mybytearray, 0, mybytearray.Length)
    52.         PictureBox2.Image = Image.FromStream(mymemorystream)
    53.  
    54.         'close stream
    55.         mymemorystream.Close()
    56.  
    57.     End Sub
    Last edited by nemaroller; Apr 9th, 2004 at 05:02 PM.

  21. #21

    Thread Starter
    Junior Member
    Join Date
    Mar 2004
    Posts
    22
    This is really educational and helpful. Thanks Nemaroller.

    From the code, it appears that any one with access to the encoded data could really decode the data. I am sure there must be a way of using some key to encode/decode the data. I am a newbie at this stuff.

    Thanks once again everyone for your help.

  22. #22
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    The encoding in the last post of mine was just text encoding, not encryption. The post where you mentioned it looked like a web app, in there, there is the encryption classes... you can use those before you send the data to the database, and then decrypt it when you get the data back.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width