How to create a folder then create a csv file inside it - c#

I have an exe that already creates a csv file. If I save the exe in C:/EXE, then the cvs file automatically gets created in C:/EXE folder.
C# code uses StreamWriter to accomplish this:
using (TextWriter log = new StreamWriter(errorLog + errorBatchNumber.ToString("000") + ".csv", true))
{
if (errorCount == 0)
{
log.WriteLine("Error message");
}
log.WriteLine(link.StatusMessage);
log.Close();
}
What I need to add:
A folder needs to be created first where the csv file will be saved.
This folder will be created where the EXE was saved, in this example: C:/EXE
After folder and cvs file was created, it needs to be zipped thru code. (But I need to accomplish first 1 and 2)
Any ideas?
Thanks in advance guys! :)

If you know the path where the EXE will be saved then
Directory.CreateDirectory(path + folderName) to create folder
To zip items use SharpZipLib at
http://www.icsharpcode.net/opensource/sharpziplib/ or http://wiki.sharpdevelop.net/SharpZipLib_MainPage.ashx

Would be something like
DirectoryInfo di = new DirectoryInfo(#"C:\exe");
if(!di.Exists)
di.Create();
Then you can use di.FullName to get the directory to save your file into.
Syntax might be a bit off but it should be enough to get you started. You can check out the MSDN on DirectoryInfo as well.

Related

c# add folders to resources?

In my project, I want to add several folders containing different files to Project-Properties-Resources, but I found that I could't add folders to resources, which is the way I really need.
So, is there any possible way that I can add folders to Project-Properties-Resources? In visual studio, I only found Add Existing File, Add New String and so on.
Thanks in advance to anyone who read my question.
You compress the folders into ZIP files, add the file, then decompress at runtime.
using System.IO.Compression....
string startPath = #"c:\example\start";//folder to add
string zipPath = #"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
//add the ZIP file you just created to your resources
//Then, on startup, extract the zip to a folder you control
string extractPath = #"c:\example\extract";
ZipFile.ExtractToDirectory(zipPath, extractPath);
To do this once per update, do something like create a setting for delete, set it to true on distribution, then:
private void shouldExtract()
{
if (MyProject.Properties.Settings.Default.DeleteExtractionFolder == true)
{
if (Directory.Exists(myExtractionDirectory))
{
Directory.Delete(myExtractionDirectory);
//unzip
MyProject.Properties.Settings.Default.DeleteExtractionFolder = false;
}
}
}
Adding a whole folder (with subfolders) as embedded resource?

Link to local text file in Solution c#

I need to save a set of 20 txt files into my solution so they will be included into the exe file. In such a way I will be able to send to the final users only the executable file and anything else.
I need to use the following function:
File.Copy( sourcePath, #path + "\\FileName.txt");
to copy one of the 20 files into another directory (according to the request of the user). In order to include the 20 txt files into the solution, I created a new folder into the Solution Explorer and I put them into it. Then I selected "Resources" into the option of the single txt file. Let's suppose the name of the folder is FOO and the file is NAME01, then I'm assuming the local address of the single txt file is "\FOO\NAME01.txt". But this is not working, I'm getting an arror from the File.Copy function related to the sourcePath.
Do you have any suggestions? I'm stacked on this problem and I cannot find any solution on the web. Many thanks!
Step 1: add the files to your project
Step 2: make them embedded resource
Step 3: export them to filesystem at runtime:
using System.Reflection;
namespace ConsoleApplication1
{
class Program4
{
public static void Main(string[] args)
{
using(var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("ConsoleApplication1.Files.TextFile1.txt"))
using (var filestream = System.IO.File.OpenWrite("target.txt"))
{
stream.CopyTo(filestream);
filestream.Flush();
filestream.Close();
stream.Close();
}
}
}
}
"ConsoleApplication1.Files.TextFile1.txt" comes from:
ConsoleApplication1: default namespace of the project containing the files
Files.TextFile1.txt: relative path, dotted, inside the dll (look # screenshot 1)

Creating zip file from multiple files

The code below is working fine in creating a zip file but the file created is having a folder IIS Deploy >>>WebService... then the text file and not just the text file.
How can I just add the text files to the zip file?
ZipFile z = ZipFile.Create("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\Accident.zip");
//initialize the file so that it can accept updates
z.BeginUpdate();
//add the file to the zip file
z.Add("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\test1.txt");
z.Add("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\test2.txt");
z.Add("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\test3.txt");
//commit the update once we are done
z.CommitUpdate();
//close the file
z.Close();
If you have everything within same folder then the easiest option is to use CreateFromDirectory class.
static void Main()
{
// Create a ZIP file from the directory "source".
// ... The "source" folder is in the same directory as this program.
// ... Use optimal compression.
ZipFile.CreateFromDirectory("source", "destination.zip",
CompressionLevel.Optimal, false);
// Extract the directory we just created.
// ... Store the results in a new folder called "destination".
// ... The new folder must not exist.
ZipFile.ExtractToDirectory("destination.zip", "destination");
}
http://www.dotnetperls.com/zipfile
Please note that it is applicable to .NET Framework 4.6 and 4.5

SharpZipLib - adding folders/directories to a zip archive

From examples, I've got a pretty good grasp over how to extract a zip file.
In nearly every example, the method of identifying when a ZipEntry is a directory is as follows
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName.Length > 0)
Directory.CreateDirectory(Path.Combine(destinationDirectory, directoryName));
if (fileName != String.Empty)
{
//read data and write to file
}
Now is is fine and all (directory encountered, create it), directory is available when the file is extracted.
I can add files to a zip fine, but how do I add folders? I understand I'll be looping through the directories, adding the files encountered (and their ZipEntry.Name property is populated properly), but how do I add a ZipEntry to the archive and instruct the ZipOutputStream that it is a directory?
ZipFile.AddDirectory does what you want. Small sample code here.

DirectoryNotFound Exception in C#

I'm trying to save a file at path WindowsFormsApplication1\WindowsFormsApplication1\SaveFile but the following code returning me a "DirectoryNotFound" Exception with the message :
Could not find a part of the path
'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}
Could anyone please tell me how should I save a file at my desirable folder with specifying complete path?
When you are running in the debugger, your default path is under bin\Debug. That's what "." means in your path.
Which folder do you want to save to? You'll need to specify the full path. Perhaps you'll want to pull the path from a config file. That way, the path will be able to change based on where your application is deployed.
As the error message tells you the file will be saved in the subdirectory SaveFile under bin/debug. Before you can save a file you have to create a directory with Directory.CreateDirectory("SaveFile"). It will not be automatically created.
You need to make sure the directory exists prior to creating the text file.
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
if (!info.Directory.Exists)
info.Directory.Create();
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}

Categories