Open "file" from memory stream? - c#

I am wondering if its even possible. I am returning files from database (blob) and have them as bytes array. I would like to let the user to show the data content by clicking on associated object - something like opening in the WebBrowser which automatically selects the appropriate program..but I understand I would need to save the file to the disk.
Is there any other solution which would work only from streams/byte arrays?

You could try setting the WebBrowser.DocumentStream property:
browser.DocumentStream = new MemoryStream(blob);

Related

Saving Data On C# Wpf

How can I save my added buttons when closing the program ? Each time I hit an add button I'm creating a new title which type is button.And each title have it's own specific words.So I must save the words in buttons at the same time.
Find out what data needs to be stored. > Define a Model
Define how the Data will be stored > e.g. XML-Serialisation, JSON or whatever
Define where Data will be stored, e.g. Database, File
Define when the Configuration is read and saved
eg: read on startup, save on shutdown
Handle your Configuration Data to generate your buttons
Its all up to you. :)
An easy solution might be using XmlSerializer, which is documented here.

How to get all files from a folder in sorted order in C#.Net? [duplicate]

Is is possible to get files that is ordered same as in Windows Explorer
I know "natural sort", but it's not what I need, I need to get the file list ordered by the same attribute in Windows Explorer, for example:
If I ordered a directory by the attribute "create date", then I will get a file list as below:
name create date file size
1.txt 2012/1/1 125Kb
2.tab 2012/3/2 15Kb
3.bmp 2013/5/5 26Kb
If my windows explorer order file list with the attribute "file size", the the file list would be:
name create date file size
2.tab 2012/3/2 15Kb
3.bmp 2013/5/5 26Kb
1.txt 2012/1/1 125Kb
Could anyone help?
I think this is going to be a lot more complex than you expect. Folder settings are stored in the registry in two places:
HKCU\Software\Microsoft\Windows\Shell\BagMRU
HKCU\Software\Microsoft\Windows\Shell\Bags
The first path contains a structure which reflects the structure of the file system, and the second path contains details about those items, including a REG_BINARY value called "Sort" which records the sort order used for that folder.
See Willi Balenthin's website for details on the structure, including sample code (in Python)
Here's how to get a list of files sorted by their name:
var path = #"C:\windows"; // obviously change this to whatever you want
var files = System.IO.Directory.GetFiles (path).ToList ();
file.Sort();
And that's it!
Here's how you would do it per your given code sample:
var temperaturePressureSignalFilesList = Directory.GetFiles(TemperaturePressureSignalDirectory, "*.txt", SearchOption.TopDirectoryOnly).ToList();
temperaturePressureSignalFilesList.Sort();
using System.Linq;
DirectoryInfo info = new DirectoryInfo(""); FileInfo[] files =
info.GetFiles().OrderBy(p => p.CreationTime).ToArray(); foreach
(FileInfo file in files) {
// DO Something... }
here is the sample code for get files in directory by creation time.
You can get files by size same way.
I guess you are talking about viewing pane in Windows Explorer (it's essentially a Windows File Manager but also known under different name). Some clarification is needed. You can apply your custom sorting on various columns; moreover, you can have multiple viewing panes (windows) open sorted on different columns. Thus, the problem definition is a bit unclear.
Assuming that you know the sorting order in your viewing panes, then you can use System.IO.DirectoryInfo and derived FileSystemInfo[] objects; the latter has files.OrderBy method.
Hope this will help. My best, Alex
If you want natural sort order, you should either P/Invoke StrCmpLogicalW (http://msdn.microsoft.com/en-us/library/bb759947.aspx) or find a managed natural sort algorithm. There is no built-in natural sort in .NET Framework.
I think you cannot know which is the order in the pane (by size, name or whatever), you must read the list and then sort it the way you want or prompt the user to select a sorting attribute.
As Kenny posted Sorting Directory.GetFiles() here is an approach, anyway I still thinking there is no possibly way to know which is the sorting order that user selected in the viewing pane.
I think you would have to write a shell extension for windows explorer that captures sort events on columns and writes that metadata to disk in some structured way. You may have multiple explorer windows open so might be an idea to apply timestamp or id so you know which explorer window you are dealing with. Then in your app read that metadata to get the sort order and apply accordingly. Not easy but doable.

Copy object using Clipboard and paste it as object or text

I want to copy object ( List ) to clipboard and use it in my application and outside of it.
In my application, I want to be able to "paste" data without any additional operation. Outside I need CSV data.
I tried to achieve it by using DataObject. I can convert this list to formatted string - so i think it's easy to get CSV. I stored random string in DataObject, (just for test). The problem is storing List object in Clipboard. DataObject contains specific type ( checked using DataObject.GetFormats() ), but when i try to get this object from clipboard, I get null.
I've found this, while it solves my problem, I need to serialize/deserialize.
Is there any way to store and retrieve object the normal way ?
Clipboard.SetDataObject(list);
var deslist = Clipboard.GetDataObject().GetData(list.GetType());

Can I pass a .net Object via querystring?

I stucked at a condition , where i need to share values between the pages. I want to share value from Codebehind via little or no javascript. I already have a question here on SO , but using JS. Still did'nt got any result so another approach i am asking.
So I want to know can i pass any .net object in query string. SO that i can unbox it on other end conveniently.
Update
Or is there any JavaScript approach, by passing it to windows modal dialog. or something like that.
What I am doing
What i was doing is that on my parent page load. I am extracting the properties from my class that has values fetched from db. and put it in a Session["mySession"]. Some thing like this.
Session["mySession"] = myClass.myStatus which is List<int>;
Now on one my event that checkbox click event from client side, i am opening a popup. and on its page load, extracting the list and filling the checkbox list on the child page.
Now from here user can modify its selection and close this page. Close is done via a button called save , on which i am iterating through the checked items and again sending it in Session["mySession"].
But the problem is here , when ever i again click on radio button to view the updated values , it displays the previous one. That is , If my total count of list is 3 from the db, and after modification it is 1. After reopening it still displays 3 instead of 1.
Yes, you could but you would have to serialize that value so that it could be encoded as a string. I think a much better approach would be to put the object in session rather than on the URL.
I would so something like this.
var stringNumbers = intNumbers.Select(i => i.ToString()).ToArray();
var qsValue = string.Join(",", stringNumbers);
Request.Redirect("Page.aspx?numbers=" + sqValue);
Keep in mind that if there are too many numbers the query string is not the best option. Also remember that anyone can see the query string so if this data needs to be secure do not use the query string. Keep in mind the suggestions of other posters.
Note
If you are using .NET 4 you can simplify the above code:
var qsValue = string.Join(",", intNumbers);
Make the object serializable and store it in an out-of-process session.
All pages on your web application will then be able to access the object.
you could serialize it and make it printable but you shouldn't
really, you shouldn't
The specification does not dictate a minimum or maximum URL length, but implementation varies by browser and version. For example, Internet Explorer does not support URLs that have more than 2083 characters.[6][7] There is no limit on the number of parameters in a URL; only the raw (as opposed to URL encoded) character length of the URL matters. Web servers may also impose limits on the length of the query string, depending on how the URL and query string is stored. If the URL is too long, the web server fails with the 414 Request-URI Too Long HTTP status code.
I would probably use a cookie to store the object.

C# Storage of User Entered Data

I'm trying to write a C# program, where when a user enters some data into a text box and clicks on a "save" button, the information is stored in some sort of file that when the program is opened the next time around, the information is automatically loaded in.
I'm using Visual C# express. What's the best way to do this without requiring some sort of database like MySQL or MSSQL or Access?
If the only way or easiest way is a database, I'd rather use Access. If so, does the user of the program need Access installed for my program to run on their computer? What if I go with another database?
p.s.
I forgot to mention, I'd rather the user not be able to access this file and read the contents easily. Text file without encryption would be easy to open. Any way to encrypt this? Also, if I use a delimiter like ':', then that means the user cannot use that character. So any other way?
Thanks!
Make your user data serializable by adding the keyword:
[Serializable]
above your data structure. When you load the dialog box, load your serialized structure from disk, and when you leave the dialog, save the data structure.
From a style standpoint, you should probably not have the dialog box change data until the dialog box is closed (if it's modal).
To save:
private bool Save(String inFileName, MyObject inObject){
try {
FileStream theStream = File.Open(inFileName, FileMode.Create);
BinaryFormatter theFormatter = new BinaryFormatter();
theFormatter.Serialize(theStream, inObject);//add it to the end there
theStream.Dispose();
theStream.Close();
} catch{
return false;
}
return true;
}
To Load:
private MyObject Read(String inFileName){
MyObject theReturn = null;
try {
FileStream theStream = File.Open(inFileName, FileMode.Open, FileAccess.Read);
BinaryFormatter theFormatter = new BinaryFormatter();
theReturn = (CImageData)theFormatter.Deserialize(theStream);//add it to the end there
theStream.Dispose();
theStream.Close();
}
catch {
return null;
}
return theReturn;
}
You can also use 'using' on a stream, but this code is pretty straightforward, I think. It also means that you can add more items into MyObject.
Edit: For encryption, you can add in AES or something similar. That might be overkill for you, and saving the file as binary may make it readable by something like notepad, but not easily editable. Here's a lengthy explanation on real encryption:
http://msdn.microsoft.com/en-us/magazine/cc164055.aspx
Sql Compact Edition would hide the data from being easily accessible (and its free). You can also password protect a CE database. A SQL CE database is contained completely in an .SDF file, like Access, so you can copy the .sdf file around and not have to worry about network connectivity, etc.
If your application is only to be used by a single person then simply store your data in a file (XML would give you some structure)
If your application will be used by multiple people and the data shared among them, then a database is your best option. If you use a database then yes you will need to have a database installed on your users computer, though it is possible to do that transparantly to your user, for that you are best off with an embeddable database, something like MySQL would be your best bet.
(EDIT: the database actually does not have to be on the users computer, but he would need to be able to see it from his coputer)
If it's very simple then you could place it in a plain text file. For more structured data you could consider storing it as a CSV and parsing it or creating an XmlDocument and saving that to disk.

Categories

Resources