GetTempFileName() and proper file extensions - c#

I'm using GetTempFileName() in order to write bytes from a database to a temporary file. These files are normally PDF type, however, they can and do vary.
I'm running into an issue where attempting Process.Start(tempPath) throws an error because Windows cannot find an associated program with a .tmp file.
As opposed to writing a custom method that verifies the mime type and adjusts the file name as needed, is there any common/standard way to handle this .tmp file type in .NET?

I guess that Reed Copsey's answer on a related question helps to answer yours:
You can append the extension to the autogenerated temp-file:
string filename = System.IO.Path.GetTempFileName() + ".pdf"; // Makes something like "C:\Temp\blah.tmp.pdf"
File.WriteAllBytes(filename, filedata);
var process = Process.Start(filename);
// Clean up our temporary file...
process.Exited += (s,e) => System.IO.File.Delete(filename);

Related

.NET Core 2.2 Razor Page Code Behind Creates Text File, But Fails to Write Simple Line To File

Not sure what I am doing wrong. I can create a text file named using Now date and time. My writing to the file fails. If I don't put ".Close()" at the end of the CreateText, it says the file is open by another process when trying to write. With the ".Close()" there are no errors but it doesn't write.
var newFileName = "logs\\" + DateTime.Now.ToString().Replace("/","_").Replace(":","-").Replace(" ","__") + ".txt";
var webRootPath = _environment.WebRootPath;
var dataPath = Path.Combine(webRootPath, newFileName);
System.IO.File.CreateText(dataPath).Close();
System.IO.File.AppendText(dataPath).WriteLine("this is before save");
Just use this:
//System.IO.File.CreateText(dataPath).Close();
System.IO.File.AppendText(dataPath).WriteLine("this is before save");
CreateText() will create a new empty file each time.
AppendText() will create the file if necessary.
But you are leaking file handles here. Appendtext returns a TextWriter that needs to be closed.
Instead of fixing that, consider using a reliable logging packages.

how to Save File using C# Windows Application

I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));

Read .txt embedded as resource

I have embedded a resource into my code, I want to read the text and apply the text to some string variables. I have worked out how to do that when I use an external file but I only want the .exe
string setting_file = "config.txt";
string complete = File.ReadAllText(setting_file);
string Filename = complete.Split('#').Last(); //"Test.zip";
string URL = complete.Split('#').First();
How can I read the resource config.txt
(Preferably without new procedures)
The File class is only used for accessing the file system whereas your file is no longer in the system so this line needs to change. As others have hinted with linked answers you need to get the stream for the resource and then read that. The below method can be called to replace your File.ReadAllText method call.
private static string GetTextResourceFile(string resourceName)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd();
}
}
The resourceName will be something along the lines of MyNamespace.Myfile.txt. If you are having problems finding your resourcename then the method GetManifestResourceNames on the assembly will help you identify it while debugging.
Also of note is the above method will throw an exception if the resource isn't found. This should be handled in real code but I didn't want to confuse the above sample with standard error handling code.
See also How to read embedded resource text file for a different question with the same answer (that differs in that it asks only about streams but in fact streams seem to be the only way to access embedded resource files anyway).
This is how you can use embedded files Properties.Resources.yourfilename

overwriting file with File.CreateText (C#)

I am experiencing the following problem. I am using .NET Framework 1.1 and I am trying to overwrite a file using this code:
try
{
using (StringWriter writer = new StringWriter())
{
Server.Execute(path, writer);
using (StreamWriter sr = File.CreateText(filepath + fileName))
{
sr.WriteLine(writer.ToString());
}
}
}
catch (Exception exc)
{
...
}
Sometimes it works fine, but sometimes it does not overwrite the file and no exception is thrown. Could someone tell me what the issue may be or how to handle why it doesn't overwrite the file?
Why not just:
File.WriteAllText(Path.Combine(filepath, fileName), writer.ToString())
From MSDN:
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
Could someone tell me what the issue may be or how to handle why it
doesn't overwrite the file?
Well, to answer your actual question, File.CreateText(string file) is behaving exactly as intended. if filepath + fileName to use your example, is a file that already exists, it opens the file instead of creating it. (It does not overwrite).
You could first check to see if the file exists using File.Exists(string file) then File.Delete(string file).
If File.CreateText(string file) doesn't suit your needs, you could try a different type. Maybe FileInfo?
Microsoft Says:
Creates or opens a file for writing UTF-8 encoded text.
Source: https://msdn.microsoft.com/en-us/library/system.io.file.createtext%28v=vs.110%29.aspx
over write can also be achieved with built in file.copy method.
File.copy has overload -
File.Copy Method (Source, Destination, OverWrite)
more info on msdn
hope this helps.

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