How to open a file from silverlight folder - c#

I have a xlsx file (New.xlsx) in a folder (Common) in my project (Silverlight side).
I want to access that file path on button click event and want to open that file.
I used below path :
string path = #"/Common/New.xlsx";
string path1 = excel.Workbooks.Open(path);
excel.Visible = true;
But it is not working and I cannot open that file.
How to access file using file path in Silverlight?

You have a few options available to you for giving access to the file in question.
You can get the content of the file as a stream and then ask the user to save the file via the SaveFileDialog class. The user would then have to select where they want to save the file and then open it manually.
public static byte[] GetBytesFromStream(Stream input){
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream()){
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0){
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
public void OnButtonClick(){
var templateUri = new Uri("/Common/New.xlsx, UriKind.Relative");
var templateStream = Application.GetResourceStream(templateUri).Stream;
var bytes = GetBytesFromStream(templateStream);
var sfd = new SaveFileDialog() {
DefaultExt = "xlsx",
Filter = "Excel Files (*.xlsx)|*.xlsx|All files(*.*)|*.*",
FilterIndex = 1
};
if (sfd.ShowDialog() == true) {
using (Stream stream = sfd.OpenFile()) {
stream.Write(bytes, 0, bytes.Length);
}
}
}
You can have the file stored server side and when the user clicks the button you tell the browser to get he file in question. The browser will then take over and ask the user if they want to save the file to disk or open using a known application.
public void OnButtonClick(){
string link = "{the url/endpoint to the file on the server}";
System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(link), "_blank");
}
You can go down the AutomationFactory route but that would require alot of configuration changes like suggested here
I think it's much better to have such things on the server rather than on the client side. The server is more well equipped to handle such processing.

Try the following:
var TemplateUri = new Uri("/Common/New.xlsx, UriKind.Relative");
var stream = Application.GetResourceStream(sheetUri).Stream;
The file is deployed witin the xap file (which is a zip file) and cannot be handled by a normal file on the disk.
It is not clear for me what Excel library you are using, but it should allow you to load data from Stream.

Related

Unable to scan Outlook Attachment for encryption

I am trying to detect an encrypted attachment using ICSharpCode.SharpZipLib,
but the code breaks while debugging on this line:
FileStream fileStreamIn = new FileStream(attachtype, FileMode.Open, FileAccess.Read);
Is there any other way through which I can get Outlook attachment and scan for encryption?
if (attachments.Count != 0)
{
for (int i = 1; i <= mail.Attachments.Count; i++)
{
String attachtype = mail.Attachments[i].FileName.ToLower();
if (extensionsArray.Any(attachtype.Contains))
{
FileStream fileStreamIn = new FileStream(attachtype, FileMode.Open, FileAccess.Read);
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
ZipEntry entry = zipInStream.GetNextEntry();
MessageBox.Show("IsCrypted: " + entry.IsCrypted);
}
}
}
I'm assuming you are using Microsoft.Office.Interop.Outlook namespaces.
According to the MSDN the Filename property does the following (source):
Returns a String (string in C#) representing the file name of the
attachment. Read-only.
So the value is only the name of the file, not the location (it does not exist on disk as a accessible file). When supplying just the filaneme into a FileStream it will attempt to open a file with that name in the local directory (which probably does not exist).
It seems from the documentation you'll need to store it using the SaveAsFile method (source) into a temporary file and load a FileStream from that.
So something like:
// Location to store file so we can access the data.
var tempFile = Path.GetTempFileName();
try {
// Save attachment into our file
mail.Attachments[i].SaveToFile(tempFile);
using(var stream = File.OpenRead(tempFile)) {
// Do stuff
}
} finally {
// Cleanup the temp file
File.Delete(tempFile);
}

Going from a File Path to using a Resource

My current project uses a direct file path of this excel document to read information off of the excel file. I need to get my project ready for release so I cannot have the project hard code a file path in the form of a string.
I want to embed the Excel File in my resource, which I have done, but know how can I get the file path from Resource, and send a file path to the class which reads the Excel file. The class must be feed a filepath so I was thinking of making a copy of this Excel file, and in the Temp folder then referenceing the file path for the class to read the Excel file.
FileName = #"D:\SomeFolder\ExcelFile.xlsx"; //This is the old code, hard coded
//I need code that is going to make a copy of this file from the Resources and save it somewhere in a temp folder, but then give me
the File path in the form of a string.
string FileName;
// I need the file name to have the directory of this excel that is in the Resource folder
//Call Class to Create XML File and store Data from BIN File Locally on Program
ReadExcel_CreateXML = new ExcelRecorder(FileName);
Something else to think about is that you are probably reading the current files using a FileStream and either a BinaryReader or StreamReader. If that's the case, the consumer of the file could be written to accept an arbitrary Stream instead and then you can create a MemoryStream to pass to the consuming class:
// The resource will be a byte array, I'm just creating a
// byte array manually for example purposes.
var fileData = System.Text.Encoding.UTF8.GetBytes("Hello\nWorld!");
using (var memoryStream = new MemoryStream(fileData))
using (var streamReader = new StreamReader(memoryStream))
{
// Do whatever you need with the file's contents
Console.WriteLine(streamReader.ReadLine());
Console.WriteLine(streamReader.ReadLine());
}
This approach means you won't be cluttering up the client computer with temporary files that you'll need to clean up. It also means your consuming class will become more flexible if you ever need to process data over any other type of Stream.
I'm not sure if this the best solution, but it will work:
1st get the byte[] array of the file in your resources:
byte[] fileByteArray = global::YourProjectNameSpace.Properties.Resources.ExcelFileName
2nd Export the file to a temporary location using this function:
(I got from here: Write bytes to file)
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
try
{
// Open file for reading
System.IO.FileStream _FileStream =
new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
System.IO.FileAccess.Write);
// Writes a block of bytes to this stream using data from
// a byte array.
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
// close file stream
_FileStream.Close();
return true;
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}",
_Exception.ToString());
}
// error occured, return false
return false;
}
And last access that temporary file like you normally would
Use:
Just create a button in a form and put this code in the button's click event
private void button1_Click(object sender, EventArgs e)
{
byte[] fileByteArray = global::YourProjectNameSpace.Properties.Resources.ExcelFileName;
if (ByteArrayToFile(#"C:\Temp\file.xlsx", fileByteArray))
{
//File was saved properly
}
else
{
//There was an error saving the file
}
}
Hope it works

How to open up a zip file from MemoryStream

I am using DotNetZip.
What I need to do is to open up a zip files with files from the server.
The user can then grab the files and store it locally on their machine.
What I did before was the following:
string path = "Q:\\ZipFiles\\zip" + npnum + ".zip";
zip.Save(path);
Process.Start(path);
Note that Q: is a drive on the server. With Process.Start, it simply open up the zip file so that the user can access all the files. I like to do the same but not store the file on disk but show it from memory.
Now, instead of storing the zip file on the server, I like to open it up with MemoryStream
I have the following but does not seem to work
var ms = new MemoryStream();
zip.Save(ms);
but not sure how to proceed further in terms of opening up the zip file from a memory stream so that the user can access all the files
Here is a live piece of code (copied verbatim) which I wrote to download a series of blog posts as a zipped csv file. It's live and it works.
public ActionResult L2CSV()
{
var posts = _dataItemService.SelectStuff();
string csv = CSV.IEnumerableToCSV(posts);
// These first two lines simply get our required data as a long csv string
var fileData = Zip.CreateZip("LogPosts.csv", System.Text.Encoding.UTF8.GetBytes(csv));
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "LogPosts.zip",
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, "application/octet-stream");
}
You can use:
zip.Save(ms);
// Set read point to beginning of stream
ms.Position = 0;
ZipFile newZip = ZipFile.Read(ms);
See the documentation for Create a zip using content obtained from a stream.
using (ZipFile zip = new ZipFile())
{
ZipEntry e= zip.AddEntry("Content-From-Stream.bin", "basedirectory", StreamToRead);
e.Comment = "The content for entry in the zip file was obtained from a stream";
zip.AddFile("Readme.txt");
zip.Save(zipFileToCreate);
}
After saving it, you can then open it up as normal.

Load XPS to documentviewer from embedded resource

i am trying to make help for my application. I have xps documents which i am loading to documentviewer. These files are embedded in resource file.
I am able to access these as bytearray.
For example
Properties.Resources.help_sudoku_methods_2
returns byte[]
However, documentviewer cant read it and requires fixeddocumentsequence.
So i create memory stream from bytearray, then xpsdocument and then fixeddocumentsequence like this:
private void loadDocument(byte[] sourceXPS)
{
MemoryStream ms = new MemoryStream(sourceXPS);
const string memoryName = "memorystream://ms.xps";
Uri memoryUri = new Uri(memoryName);
try
{
PackageStore.RemovePackage(memoryUri);
}
catch (Exception)
{ }
Package package = Package.Open(ms);
PackageStore.AddPackage(memoryUri, package);
XpsDocument xps = new XpsDocument(package, CompressionOption.SuperFast, memoryName);
FixedDocumentSequence fixedDocumentSequence = xps.GetFixedDocumentSequence();
doc.Document = fixedDocumentSequence;
}
This is very unclean aproach and also doesnt work if there are images in files - instead of images in new documents displays images from first loaded doc.
Is there any cleaner way to load XPS from embedded resources to documentviewer? or do i need somethink like copy file from resources to application directory and load from here and not memorystream? Thank you.
why dont you write file to system temp folder and then read from there.
Stream ReadStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("file1.xps");
string tempFile = Path.GetTempPath()+"file1.xps";
FileStream WriteStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write);
ReadStream.CopyTo(WriteStream);
WriteStream.Close();
ReadStream.Close();
// Read tempFile INTO memory here and then
File.Delete(tempFile);

How to save a file without prompting the user for a name/path?

I'm trying to open a stream to a file.
First I need to save a file to my desktop and then open a stream to that file.
This code works well (from my previous project) but in this case, I don't want to prompt the user to pick the save location or even the name of the file. Just save it and open the stream:
Stream myStream;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
PdfWriter.GetInstance(document, myStream);
Here's my code for the newer project (the reason for this question):
namespace Tutomentor.Reporting
{
public class StudentList
{
public void PrintStudentList(int gradeParaleloID)
{
StudentRepository repo = new StudentRepository();
var students = repo.FindAllStudents()
.Where(s => s.IDGradeParalelo == gradeParaleloID);
Document document = new Document(PageSize.LETTER);
Stream stream;
PdfWriter.GetInstance(document, stream);
document.Open();
foreach (var student in students)
{
Paragraph p = new Paragraph();
p.Content = student.Name;
document.Add(p);
}
}
}
}
Use Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) to get the desktop directory.
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
"MyFile.pdf");
using(var stream = File.OpenWrite(fileName))
{
PdfWriter.GetInstance(document, stream);
}
// However you initialize your instance of StudentList
StudentList myStudentList = ...;
using (FileStream stream = File.OpenWrite(#"C:\Users\me\Desktop\myDoc.pdf")) {
try {
myStudentList.PrintStudentList(stream, gradeParaleloID);
}
finally {
stream.Close();
}
}
You should pass the stream into your method:
public void PrintStudentList(Stream stream, int gradeParaleloID) { ... }
EDIT
Even though I hard coded a path above, you shouldn't do that, use something like this to get the path to your desktop:
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
If this is a local (e.g. Windows/console) application just make the stream a FileStream to whatever path you want (check this for info on how to get the desktop folder path). If the user running the application has write permitions to that file it will be created/saved there.
If this is a web (e.g. ASP.Net) application you won't be able to save the file directly in the client machine without prompting the user (for security reasons).
Stream myStream = new FileStream(#"c:\Users\[user]\Desktop\myfile.dat", FileMode.OpenOrCreate);
Your FileMode may differ depending on what you're trying to do. Also I wouldn't advise actually using the Desktop for this, but that's what you asked for in the question. Preferably, look into Isolated Storage.

Categories

Resources