FileStream not reading FileName input from external class - c#

I'm trying to make a byte writer. So far I have made the program write the file header as a general test before I continue coding the writer. The problem is, after I select a file through coreForm's coreSaveFileDialog, the line
var fs = new FileStream(classCoreForm.CoreSaveFileDialog.FileName, FileMode.Open, FileAccess.ReadWrite);
doesn't see the FileName from the dialog, and throws an exception saying "Empty path name is not legal."
Here's the source of my method:
internal void writeHeader()
{
var classCoreForm = new coreForm(); //Creates reference instance for coreForm=
var fs = new FileStream(classCoreForm.coreSaveFileDialog.FileName, FileMode.Open, FileAccess.ReadWrite);
/*
* Writes file header via fs.WriteByte . . .
*/
}
writeHeader is being called from a preliminary function called saveScript. Here's its source.
internal void saveScript()
{
var classCoreForm = new coreForm(); //Creates reference instance for coreForm
if (fileAlreadySaved == false)
{
classCoreForm.coreSaveFileDialog.ShowDialog(); //Shows save file dialog
if (classCoreForm.coreSaveFileDialog.FileName != "")
{
writeHeader();
}
else
{
}
}
}
What am I doing wrong? Have I incorrectly set something in the SaveFileDialog's properties, or is it something within the code above?

saveScript() calls writeHeader, but it doesn't pass anything in to writeHeader. You're then creating a completely new instance of "coreForm" which is separate from the instance you created in the saveScript method.
Change writeHeader to accept a file name as an argument:
internal void writeHeader(string fileName)
{
//var classCoreForm = new coreForm(); //Creates reference instance for coreForm=
var fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);
/*
* Writes file header via fs.WriteByte . . .
*/
}
Then, in your saveScript() method, change writeHeader(); to
writeHeader(classCoreForm.coreSaveFileDialog.FileName);
If you need the coreForm for other reasons in saveScript, you may want to pass the coreForm by reference, or pass in the other variables you might need into saveScript.

Related

Writing Parquet files using Parquet.NET works with local file, but results in empty file in blob storage

We are using parquet.net to write parquet files. I've set up a simple schema containing 3 columns, and 2 rows:
// Set up the file structure
var UserKey = new Parquet.Data.DataColumn(
new DataField<Int32>("UserKey"),
new Int32[] { 1234, 12345}
);
var AADID = new Parquet.Data.DataColumn(
new DataField<string>("AADID"),
new string[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }
);
var UserLocale = new Parquet.Data.DataColumn(
new DataField<string>("UserLocale"),
new string[] { "en-US", "en-US" }
);
var schema = new Schema(UserKey.Field, AADID.Field, UserLocale.Field
);
When using a FileStream to write to a local file, a file is created, and when the code finishes, I can see two rows in the file (which is 1 kb after):
using (Stream fileStream = System.IO.File.OpenWrite("C:\\Temp\\Users.parquet")) {
using (var parquetWriter = new ParquetWriter(schema, fileStream)) {
// Creare a new row group in the file
using (ParquetRowGroupWriter groupWriter = parquetWriter.CreateRowGroup()) {
groupWriter.WriteColumn(UserKey);
groupWriter.WriteColumn(AADID);
groupWriter.WriteColumn(UserLocale);
}
}
}
Yet, when I attempt to use the same to write to our blob storage, that only generates an empty file, and the data is missing:
// Open reference to Blob Container
CloudAppendBlob blob = OpenBlobFile(blobEndPoint, fileName);
using (MemoryStream stream = new MemoryStream()) {
blob.CreateOrReplaceAsync();
using (var parquetWriter = new ParquetWriter(schema, stream)) {
// Creare a new row group in the file
using (ParquetRowGroupWriter groupWriter = parquetWriter.CreateRowGroup()) {
groupWriter.WriteColumn(UserKey);
groupWriter.WriteColumn(AADID);
groupWriter.WriteColumn(UserLocale);
}
// Set stream position to 0
stream.Position = 0;
blob.AppendBlockAsync(stream);
return true;
}
...
public static CloudAppendBlob OpenBlobFile (string blobEndPoint, string fileName) {
CloudBlobContainer container = new CloudBlobContainer(new System.Uri(blobEndPoint));
CloudAppendBlob blob = container.GetAppendBlobReference(fileName);
return blob;
}
Reading the documentation, I would think my implementation of the blob.AppendBlocAsync should do the trick, but yet I end up with an empty file. Would anyone have suggestions as to why this is and how I can resolve it so I actually end up with data in the file?
Thanks in advance.
The explanation for the file ending up empty is the line:
blob.AppendBlockAsync(stream);
Note how the function called has the Async suffix. This means it expects whatever is calling it to wait. I turned the function the code was in into an Async one, and had Visual Studio suggest the following change to the line:
_ = await blob.AppendBlockAsync(stream);
I'm not entirely certain what _ represents, and hovering my mouse over it doesn't reveal much more, other than it being a long data type, but the code now works as intended.

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);
}

how to clear text file content c#

i want clear text file contet with this method
private void writeTextFile(string filePath, string text)
{
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
using (StreamWriter tw = new StreamWriter(filePath))
{
File.WriteAllText(filePath,"");
tw.WriteLine(text);
tw.Close();
}
}
but i get this error
The process cannot access the file because it is being used by another process.
but this not open in anywhere ,
please help me
thank's
That's because you're creating a StreamWriter, then using File.WriteAllText. Your File is already being accessed with the StreamWriter.
File.WriteAllText does just that, writes the entire string you pass to it to a file. StreamWriter is unnecessary if you're going to use File.WriterAllText.
If you don't care about overwriting an existing file, you can do this:
private void writeTextFile(string filePath, string text)
{
File.WriteAllText(filePath, text);
}
If you want to use StreamWriter (which, by the way, File.WriteAllText uses, it just hides it), and append to the file, you can do this (from this answer):
using(StreamWriter sw = File.AppendText(path))
{
tw.WriteLine(text);
}
You can use StreamWriter for creating a file for write and use Truncate to write with clearing previous content.
StreamWriter writeFile;
writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Truncate, myIsolatedStorage));
writeFile.WriteLine("String");
writeFile.Close();
This use FileMode.Truncate
Truncate Specifies that an existing file it to be opened and then truncated so that its size is zero bytes.
Assuming that your file already exists and you want to clear its contents before populating it or whatever, I found the best way to do this with StreamWriter is..
// this line does not create test.txt file, assuming that it already exists, it will remove the contents of test.txt
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(Path.GetFullPath(C:\test.txt), False)
// this line will now be inserted into your test.txt file
sw.Write("hey there!")
// I decided to use this solution
// this section is to clear MyFile.txt
using(StreamWriter sw = new StreamWriter(#"MyPath\MyFile.txt", false))
{
foreach(string line in listofnames)
{
sw.Write(""); // change WriteLine with Write
}
sw.Close();
}
// and this section is to copy file names to MyFile.txt
using(StreamWriter file = new StreamWriter(#"MyPath\MyFile.txt", true))
{
foreach(string line in listofnames)
{
file.WriteLine(line);
}
}
You only need to specify false in the second parameter of the constructor for StreamWriter( route, false )
String ruta = #"C:\Address\YourFile".txt";
using (StreamWriter file = new StreamWriter(ruta, false))
{
for ( int i = 0; i < settings.Length; ++i )
file.WriteLine( settings[ i ] );
file.Close();
}
The problem is with you locking the file by initializing StreamWriter onto filePath and then trying to call File.WriteAllText which also internally attempts to lock the file and eventually end up with an exception being thrown.
Also from what it looks you are trying to clear the file's content and then write something in.
Consider the following:
private void writeTextFile(string filePath, string text) {
using (StreamWriter tw = new StreamWriter(filePath, false)) //second parameter is `Append` and false means override content
tw.WriteLine(text);
}
Why not use FileStream with FileMode.Create?
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
//Do something...
}
Look at the MSDN of FileMode Enum
Create
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.
Overwritten will cover/remove/clean/delete all existed file data.
if you would like to use StreamWriter, use new StreamWriter(fs).

How I can display Stream on the page?

I have a WCF method that I am calling, the method suppose to create a file but it create an exception. I try to find what is in the stream request that I am passing to this method. How I can alert or write this stream so I can find the content. That is my method:
Stream UploadImage(Stream request)
{
Stream requestTest = request;
HttpMultipartParser parser = new HttpMultipartParser(request, "data");
string filePath = "";
string passed = "";
if (parser.Success)
{
// Save the file somewhere
//File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
// Save the file
//SaveFile( mtp.Filename, mtp.ContentType, mtp.FileContents);
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
filePath = HttpContext.Current.Server.MapPath("Uploded\\test.jpg"); // BuildFilePath(strFileName, true);
filePath = filePath.Replace("SSGTrnService\\", "");
fileStream = new FileStream(filePath, FileMode.Create);
it produces an error on this line :
fileStream = new FileStream(filePath, FileMode.Create);
that I try to understand why file can not created.
Given the information you gave, I can only assume that your code tries to create the file test.jpg somewhere where your application is not allowed to write. A common mistake would be somewhere in the Program files folder. In modern Windows versions, that is specially protected.

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