Dynamically naming the file name ( Excel File ) in C# - c#

I want to name the file dynamically in C#.
i.e) Name of the File will be picked from Database. When i generate the Excel File and save in a working folder, the file name should be picked from the variable !!
i am searching online to find the solution !!

Presumably when you generate the file, one of the method calls (e.g. SaveAs) takes the name of the file as a parameter. So just don't hard-code that argument... use the value fetched from the database instead.
If that isn't enough information, please clarify your question.

Here you go.
string sFileName = "ExcelFile";
FileStream fExcel = new FileStream(Application.StartupPath + "\\" + sFileName, FileMode.Append, FileAccess.Write);

Related

How to create a directory and insert a file in that directory in C#?

I'm trying to create a directory/folder, and at the same time insert an uploaded document to it. My code works. However, when I upload the file it goes to the same level as the newly created folder but I need it inside of it. How can I achieve that? here's what I have tried:
protected void ASPxButtonUpload_Click(object sender, EventArgs e)
{
using (Stream Fstream = e.UploadedFile.FileContent)
{
string folder = NewFile.User;
string Uploads = Server.MapUploads("~/Uploads/" + e.UploadedFile.FileName);
bool same = Directory.Exists(Uploads);
Fstream fs = new Fstream(Uploads, FileMode.Create, FileAccess.ReadWrite);
if (!same)
{
Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(Uploads), folder));
Fstream.CopyTo(fs); //**File that I need to include in the new folder**
}
}
}
I appreciate the help, Thanks!
When you create the destination file stream:
new FileStream(Path, FileMode.Create, FileAccess.ReadWrite)
That Path variable is the name of the file to which you're going to write. But there are a few issues here:
You're definining it before you define the folder, so it doesn't include that folder name.
You seem to be confusing directories with files in some of your paths.
You seem to be defining another variable called Path a few lines later, which is probably confusing you. (And I'm surprised it compiles.)
All in all, variable names like Path and FileStream are a super bad idea. They're not only against C# conventions, but more importantly they're guaranteed to confuse you because those are also the names of classes that you're using. (Again, I'm surprised this even compiles.)
First and foremost, rename your variables to something more sensible. Good naming helps everything else in the code, because it helps you understand the code.
After that, don't define the target file stream until you need to use it, and define it with the full path you want to use. It looks like the whole process should simply be to check if the folder exists, create it if it doesn't, and then write the file. Nothing more complex than that.
Untested, but perhaps something like this:
// define your paths
string rootFolder = Server.MapPath("~/Path/");
string outputFolder = Path.Combine(rootFolder, NewFile.User);
string targetFile = Path.Combine(outputFolder, e.UploadedFile.FileName);
// create the directory if needed
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
// write the file
using (Stream inputFS = e.UploadedFile.FileContent)
{
FileStream outputFS = new FileStream(targetFile, FileMode.Create, FileAccess.ReadWrite);
inputFS.CopyTo(outputFS);
}
Keep your names clear, keep your operations simple. There's no need to over-complicate any of it.

How do I create an already populated text file?

I want to create a text file with the extension .jrq and populate it with two lines. However I want this to happen "all at once" instead of creating the text file and then adding the two lines. Basically I need to create an already populated text file.
Here is my current code:
FileStream fileStream = new FileStream(folder + filename + ".jrq", FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine("Line1");
streamWriter.WriteLine("Line2");
streamWriter.Flush();
streamWriter.Close();
The reason I need the file creation and the file appending to happen together is because I have a windows service that scans the folder that this text file will be created in and that service triggers a job the second it sees a .jrq file (and does logic based on what's written in the file). It notices the .jrq file before I've written anything in it and throws an error.
I think you are better off using a small trick. As adv12 pointed out writing all at once with one single method does not guarantee the implementation is atomic. if I were you I would create a temporary file:
FileStream fileStream = new FileStream(folder + filename + ".tmp",
FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine("Line1");
streamWriter.WriteLine("Line2");
streamWriter.Flush();
streamWriter.Close();
and then rename it using File.Move:
System.IO.File.Move(folder + filename + ".tmp",folder + filename + ".jrq");
So the job will start when the file jrq is full of data. it's not a super elegant solution but it would work.
Hope it helps.
You could write the file with a different filename, then move it once you've populated it. According to this question, file moves are atomic within NTFS, so your service would never see a half-written file.
File.WriteAllText is what you're looking for. If the file does not exist, it will create it with the text in it on creation.

Get full path from an opened file - C#

I'm working with print jobs using PrintSystemJobInfo and this class doesn't have the path of the file (print job). So, I was wondering if there is a class where I can use the filename that is open (in memory) and this class return the full path. This file opened could be .doc, .pdf, .xls, .txt, and so on.
Please, someone can point me to the right direction or have an idea... it would be very helpful...
The only way for you to find open file handles is to use the NtQuerySystemInformation call. Here is a project that has this done as an explorer context menu. In this guy's case, he looks for files open in a specific folder.
You would then have to match the file name to the file you have in your print job.
By the way, this is not C# but you can wrap and call the same calls he is using. The rest is really up to you to figure out. ;)
Assuming you have a Stream object that is a FileStream then just do a cast and interrogation:
Stream str = printJob.JobStream;
FileStream fileStream = str as FileStream
if( fileStream != null ) {
String fileName = fileStream.Name;
}

handling an uploaded file via FileStream

I am allowing the user to upload a file(doc, pdf, excel, txt) and then i am passing in FileStream to read and then write but after opening it i am calling a stored procedure so i can store the file name, date, upload user and where i will be a copy of it. My problem is how can deal with the string filename that has been pased in the FileStream and the stored procedure wants a string filename.
string docx = #"../../TestFiles/Test.docx";
try
{
FileStream fileStream = new FileStream(docx, FileMode.Open, FileAccess.Read);
docConverter.UpLoadFile(11, "Test.docx", "../../TestFiles/", 1, "../../Temp/", 89);
}
public void UpLoadFile(int studentId, string rawStoragePath, int uploadedByUserId, string storagePath, int assignmentElementsId)
{
Guid strGUID = Guid.NewGuid();
DateTime uploadDate = DateTime.UtcNow;
//calling stored procedure
stuSubSvc.UploadWork(studentId, strGUID, (need to pass file name), rawStoragePath, uploadDate, uploadedByUserId, storagePath, 0, assignmentElementsId);
}
Help with:
1 - getting file name from file in FileStream
2 - getting path of the uploaded file from FileStream
To get the filename out of full path you can use:
Path.GetFileName(".././Test.docx")
It'll give you Test.docx
you can't get the path of the file on the client machine. The FileStrame has a property called Handle that contains the native handle of the opened file, you follow the following article it will help you to get the file name by the handle, it is in C++ but the all functions are APIs can be called using P/Invoke in C# [DllImport].
http://msdn.microsoft.com/en-us/library/windows/desktop/aa366789(v=vs.85).aspx
Edit
Sorry the Handle is obsolete use SafeFileHandle instead
1 - getting file name from file in FileStream
There's no filename in a stream. You can get the filename of the uploaded file from the HttpPostedFileBase instance that your controller action receives as parameter. Take a look at Phil Haack's blog post about uploading files in an ASP.NET MVC application in which he illustrates that.
Assuming you have already stored the file on your file system, you could retrieve the filename from the Name property of the FileStream:
string filename = Path.GetFileName(fileStream.Name);
2 - getting path of the uploaded file from FileStream
There's no filename nor filepath in a stream. All you can hope of getting is the filename which is contained in the HttpPostedFileBase instance that your controller action should receive as parameter (see previous point).

How to open or run unknown file converted into byte[]

I use to store document/file in byte[] in database, and I want user can view/run that file from my application.
You need to know the file extension for the file you're writing, so the OS can run the default program based on the extension. The code would be something like this:
byte[] bytes = GetYourBytesFromDataBase();
string extension = GetYourFileExtension(); //.doc for example
string path = Path.GetTempFileName() + extension;
try
{
using(BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
{
writer.Write(yourBytes);
}
// open it with default application based in the
// file extension
Process p = System.Diagnostics.Process.Start(path);
p.Wait();
}
finally
{
//clean the tmp file
File.Delete(path);
}
You will need to store the file extension in the database too. If you don't have the file extension the problem becomes very difficult as you cannot rely on the operating system to work out which program to launch to handle the file.
You can use the following pattern:
Load data from database and save to file using the original file extension.
Start a new System.Diagnostics.Process that points to the saved file path.
As you have saved the file with the original file extension, the OS will look for a program that is registered for the extension to open the file.
As chibacity and Daniel suggest, storing the file extension in the db, and agreed -- storing the file extension, or at least some indicator that tells you the file type, is a good idea.
If these files are of a format of your own creation then you might also want to store information about which version of the file format the data is stored in. During development file formats are prone to changing, and if you don't remember which version you used to store the data then you have a hard job recovering the information.
The same problems are faced in object persistence generally.

Categories

Resources