In this method, I saved an excel file in a directory in that path, instead of writing the whole path, is there a way to make it short so it automatically saves in the debug file?
using (var file = File.Open("C:\\Users\\john\\Documents\\Visual Studio 2015\\Projects\\EXCEl PROJECT\\webform\\" + filename + ".xlsx",FileMode.Create))
{
ms.WriteTo(file); // copy the memory stream to the file stream
}
Use this property as your base directory. You may append to it as needed.
System.AppDomain.CurrentDomain.BaseDirectory
Sample:
using (var file = File.Open(AppDomain.CurrentDomain.BaseDirectory + "\\webform\\" + filename + ".xlsx", FileMode.Create))
{
ms.WriteTo(file); // copy the memory stream to the file stream
}
Related
Is it possible to attach a text file resource to my Winform exe. So when I run the "Form.exe" in another computer then it copy the text file to a specified folder. Please suggest a method to achieve the same. Thanks
If the resource name is a string:
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var reader = new StreamReader(stream))
{
string text = reader.ReadToEnd();
File.WriteAllText(fileName, text);
}
else:
File.WriteAllText(fileName, Properties.Resources.TextFile1);
And also make sure that you have set the Build Action of the resource file to "Embedded Resource".
First you need to add your file as a resource in your project.
This explains what to do
Then select your file and in the properties change the "Build Action" to "Embedded Resource". This will now embed your file in your output (.exe).
To extract the file you need to do the following;
String myProject = "Name of your project";
String file = "Name of your file to extract";
String outputPath = #"c:\path\to\your\output";
using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(myProject + ".Resources." + file))
{
using (System.IO.FileStream fileStream = new System.IO.FileStream(outputPath + "\\" + file, System.IO.FileMode.Create))
{
for (int i = 0; i < stream.Length; i++)
{
fileStream.WriteByte((byte)stream.ReadByte());
}
fileStream.Close();
}
}
Ideally you should check that the file does not already exist before you do this. Don't forget also to catch exceptions. Which can be very common when dealing with the file system.
Add the text file to your project resources
Properties -> Resources -> Add Resource
Read the data from the resource using
var text = Properties.Resources.textFile;
Write to the file with
File.WriteAllText(#"C:\test\testOut.txt", text);
I am creating a text file and after that I am trying to write some text in that file.but when writing text,it's generating exception that process cannot access file because it's being used by another process. Kindly someone help :( Thanks in advance.
Here is my code
dt_Loc = loc1_ctab.GetEmpLocInfo(Session["empcd"].ToString());
string str = DateTime.Now.ToString("dd-mmm-yyyy");
str = dt_Loc.Rows[0]["loc1_abrv"].ToString() + "-" + str;
string path = FilesPath.Path_SaveFile + str + ".txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(txt_comments.Text);
tw.Close();
}
Remove the File.Create since it opens a FileStream for the file.This results in the file being open and hence you get the exception that the file is being used by another process.
if (!File.Exists(path))
{
using(StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(txt_comments.Text);
}
}
Your code giving such error because, the method Create Creates or overwrites a file in the specified path. which will return A FileStream that provides read/write access to the file specified in path. So at the time of executing the writemethod, the file is being used by the returned FS. you can use this in the following way:
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes(txt_comments.Text);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can Make it simple by using File.WriteAllText which will Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
string path =FilesPath.Path_SaveFile + str + ".txt";;
if (!File.Exists(path))
{
File.WriteAllText(path, txt_comments.Text);
}
I am using .NET 4.5, and the ZipFile class works great if I am trying to zip up an entire directory with "CreateFromDirectory". However, I only want to zip up one file in the directory. I tried pointing to a specific file (folder\data.txt), but that doesn't work. I considered the ZipArchive class since it has a "CreateEntryFromFile" method, but it seems this only allows you to create an entry into an existing file.
Is there no way to simply zip up one file without creating an empty zipfile (which has its issues) and then using the ZipArchiveExtension's "CreateEntryFromFile" method?
**This is also assuming I am working on a company program which cannot use third-party add-ons at the moment.
example from:http://msdn.microsoft.com/en-us/library/ms404280%28v=vs.110%29.aspx
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
But if startPath were to be #"c:\example\start\myFile.txt;", it would throw an error that the directory is invalid.
Use the CreateEntryFromFile off a an archive and use a file or memory stream:
Using a filestream if you are fine creating the zip file and then adding to it:
using (FileStream fs = new FileStream(#"C:\Temp\output.zip",FileMode.Create))
using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create))
{
arch.CreateEntryFromFile(#"C:\Temp\data.xml", "data.xml");
}
Or if you need to do everything in memory and write the file once it is done, use a memory stream:
using (MemoryStream ms = new MemoryStream())
using (ZipArchive arch = new ZipArchive(ms, ZipArchiveMode.Create))
{
arch.CreateEntryFromFile(#"C:\Temp\data.xml", "data.xml");
}
Then you can write the MemoryStream to a file.
using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write)) {
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
ms.Close();
}
Using file (or any) stream:
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
{
var entry = zip.CreateEntry("file.txt");
entry.LastWriteTime = DateTimeOffset.Now;
using (var stream= File.OpenRead(#"c:\path\to\file.txt"))
using (var entryStream = entry.Open())
stream.CopyTo(entryStream);
}
or briefer:
// reference System.IO.Compression
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
zip.CreateEntryFromFile("file.txt", "file.txt");
make sure you add references to System.IO.Compression
Update
Also, check out the new dotnet API documentation for ZipFile and ZipArchive too. There are a few examples there. There is also a warning about referencing System.IO.Compression.FileSystem to use ZipFile.
To use the ZipFile class, you must reference the
System.IO.Compression.FileSystem assembly in your project.
The simplest way to get this working is to use a temporary folder.
FOR ZIPPING:
Create a temp folder
Move file to folder
Zip folder
Delete folder
FOR UNZIPPING:
Unzip archive
Move file from temp folder to your location
Delete temp folder
In .NET, there are quite a few ways to tackle the problem, for a single file. If you don't want to learn everything there, you can get an abstracted library, like SharpZipLib (long standing open source library), sevenzipsharp (requires 7zip libs underneath) or DotNetZip.
just use following code for compressing a file.
public void Compressfile()
{
string fileName = "Text.txt";
string sourcePath = #"C:\SMSDBBACKUP";
DirectoryInfo di = new DirectoryInfo(sourcePath);
foreach (FileInfo fi in di.GetFiles())
{
//for specific file
if (fi.ToString() == fileName)
{
Compress(fi);
}
}
}
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and
// already compressed files.
if ((File.GetAttributes(fi.FullName)
& FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Extension != ".gz")
{
// Create the compressed file.
using (FileStream outFile =
File.Create(fi.FullName + ".gz"))
{
using (GZipStream Compress =
new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into
// the compression stream.
inFile.CopyTo(Compress);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
}
I am creating a excel file in the code as Shown Below
Microsoft.Office.Interop.Excel.Application excelFile = CreateExcelFile();
now I want to convert this excelFile to byte[] without saving to hard drive. How is it possible?
had the same problem some time ago. You have to create a temporary file, and then read it to a byte array.
Example code:
string tempPath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + "_temp";//date time added to be sure there are no name conflicts
workbook.SaveAs(tempPath, workbook.FileFormat);//create temporary file from the workbook
tempPath = workbook.FullName;//name of the file with path and extension
workbook.Close();
byte[] result = File.ReadAllBytes(tempPath);//change to byte[]
File.Delete(tempPath);//delete temporary file
That isn't an Excel File it is a COM object used for Excel Automation. It can be used to request Excel to save a document to disk (as a temporary file), which you could then load into a byte[] and then delete the temporary file.
The following code could be used to do this for the active workbook:
public byte[] GetActiveWorkbook(Microsoft.Office.Interop.Excel.Application app)
{
string path = Path.GetTempFileName();
try
{
app.ActiveWorkbook.SaveCopyAs(path);
return File.ReadAllBytes(path);
}
finally
{
if(File.Exists(path))
File.Delete(path);
}
}
Basically I want to create a file if not existing then write message to it.
if (!File.Exists(filePath + fileName))
File.Create(filePath + fileName);
StreamWriter sr = new StreamWriter(filePath + fileName,false);
How to deal with this error?
The process cannot access the file 'c:\blahblah' because it is being used by another process.
File.Create opens a FileStream (http://msdn.microsoft.com/en-us/library/d62kzs03.aspx).
As you didn't dispose it, the file remains locked and subsequent accesses to the file will fail because of this situation if these are performed from other handles (i.e. other FileStream or the whole StreamWriter).
This code demonstrates how you should work with IDisposable objects like FileStream:
if (!File.Exists(filePath + fileName))
{
File.Create(filePath + fileName).Dispose();
using(StreamWriter sr = new StreamWriter(filePath + fileName,false))
{
}
}
Why not just use the StreamWriter constructor that takes in the file name?
StreamWriter sr = new StreamWriter(filePath + fileName);
From MSDN:
The path parameter can be a file name, including a file on a Universal Naming Convention (UNC) share. If the file exists, it is overwritten; otherwise, a new file is created.
Very minor point but you could consider using Path.Combine when concatenating file names and folder paths.
Simplify your code by using single method to create and open a file:
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info = new UTF8Encoding(true)
.GetBytes("This is to test the OpenWrite method.");
fs.Write(info, 0, info.Length);
}
MSDN: (File.OpenWrite Method)
Opens an existing file or creates a new file for writing.