C# console application generate CSV - c#

I have a function that returns a File. The file is created by a String, like this:
return File(System.Text.Encoding.Default.GetBytes(data.getCSV()), "text/csv", "Report.csv");
How can i generate this File to a .csv file in my folder?

According to your use of the File() method, you seem to use an (Api)Controller in a console application. Don't do this. Put business logic in a class library:
public byte[] GenerateCsv()
{
// ...
return System.Text.Encoding.Default.GetBytes(data.getCSV());
}
Then you can do something like this:
var csvData = BusinessLogic.GenerateCsv();
System.IO.File.WriteAllBytes("Report.csv", csvData);
And the same from your (Api)Controller:
var csvData = BusinessLogic.GenerateCsv();
return File(csvData, "text/csv", "Report.csv");

var directory = Directory.GetCurrentDirectory(); // assuming that the folder you are looking for is the project directory.
using(var fs = new FileStream(directory + fileName + extension))
{
using(var sw = new StreamWriter(fs))
{
//use sw to write in the appropriate way.
}
}

Maybe you mean
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
you can get path to your folder, then you can find csv file in this folder and then overwrite it(or do something else).

Related

File is always named with the Path

My File is always named like the path and my additional informations i want to have in the Filename but why is it like that?
The Path should be the chosen folder and i want to create a folder then, how can i add a folder than and say + that folder path?
The file is also always created 1 layer above the one i want. For example: C:\Test but the file is saved then in C:\ instead of C:\Test.
public static string path= string.Empty;
string fileName = DateTime.Now.ToString("yyyy.MM.dd") + "test.txt";
try
{
FileStream fs = new FileStream(path + fileName, FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter sw= new StreamWriter(fs);
sw.WriteLine("Test and so on ..");
}
catch(Exception ex) { }
Rather than using string concatenation, use Path.Combine. Aside from anything else, that will be portable if you ever want to use Mono, too.
Oh, and there are simpler ways to create a text file too:
using (var writer = File.CreateText(Path.Combine(path, fileName))
{
writer.WriteLine(...);
}
Finally, I'd strongly advise using - instead of . in your filename, so that anything which looks at the first . and expects the rest to be an extension doesn't get confused:
string fileName = DateTime.ToString("yyyy-MM-dd") + "-test.txt";

couldn't create files in my documents if my documents folder is redirect to another location in setup project

I'm creating a setup project, in the installation, I should create a file in My Documents folder, my code in Commit method looks like this:
base.Commit(savedState);
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\MyApp";
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\MyApp\Backup.xml";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (!File.Exists(path))
{
File.Create(path).Close();
}
using (TextWriter file = new StreamWriter(path, true))
{
file.WriteLine("adfasdfafdasdfaf");
}
This works well. But if I redirect My Documents to another location, such as D:\TestFolder, the code couldn't create the file in my new location, and the installation complete successfully. Anyone can help?
Edit:
I found Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) return me a wrong value. In Console Application, this return me a correct value, but in setup project, it return me an empty string.

c# .dat file assign to variable

how can i assign a to a variable, which is located at the same project, for example at my project i created a folder named App_Data and for example the file is file.dat , how can i assign the file at a variable,.. for example:
var file = App_Data/file.dat
I need it to be assigned to a variable because i will be using that variable as a parameter to a method,.. it used to be :
var file= HttpContext.Current.Request.MapPath("/App_Data/file.dat");
but now i want the path to be at the same project
if it should be absolute path it should be fine too
The MapPath should give you the absolute location of the file on disk from a relative url to the root of your website:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
This should return something like:
c:\inetpub\wwwroot\MyWebSite\App_Data\file.dat
UPDATE:
It looks like you are trying to retrieve the contents of the file, not the location. Here's how this could be done:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
string fileContents = System.IO.File.ReadAllText(absoluteFileLocation);
You need to read the file using one of the available methods (Streams, Readers, etc).
The easiest would be:
string fileContent = File.ReadAllText(fileNameAndPath);
where the variable fileNameAndPath contains the full path and file name to the file as described by Darin Dimitrov.
Your intention isn't exactly clear, anyway:
if you want file stats:
System.IO.File file = new System.IO.File("~/App_Data/file.dat");
if you want the file content use:
public static string readFileContent(String filename)
{
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
return sr.ReadToEnd();
}
catch { return String.Empty; }
}

Path with white spaces can't create a file using File.CreateText(filePath) c#

I'm developing a console application that parse xml files and generate a txt file. I have created the file path to store the new file, but this is having white spaces, like this:
string filePath = "C:\\Program Files\\my path\\fileName.txt"
but I'm creating the path using:
string filePath = Path.Combine(temp, "fileName.txt");
while temp is the previous path. And when I call:
StreamWriter sw = File.CreateText(filePath);
Is giving this exception:
Could not find a part of the path: filePath
Can someone help me with this issue?? how can I create the file with this path?
there looks like a problem with you file path
try#"C:\Program Files\my path\fileName.txt"
Note: You've updated your question with the changes mentioned in the comments.
Your issue is probably that 'my path' doesn't exist as this console application works OK for me when run as an administrator. When not run I get an UnathorizedAccessException
class Program
{
static void Main(string[] args)
{
try
{
var temp = #"C:\\Program Files\\my path\\";
string filePath = Path.Combine(temp, "fileName.txt");
StreamWriter sw = File.CreateText(filePath);
Console.WriteLine("I got here");
}
catch (Exception)
{
Console.WriteLine("I didn't");
//
}
}
}
Use this:
string filePath = #"C:\Program Files\my path\fileName.txt"
You have single backslashes in the string. Make them double backslashes:
string filePath = "C:\\Program Files\\my path\\fileName.txt"

DotNetZip: How to extract files, but ignoring the path in the zipfile?

Trying to extract files to a given folder ignoring the path in the zipfile but there doesn't seem to be a way.
This seems a fairly basic requirement given all the other good stuff implemented in there.
What am i missing ?
code is -
using (Ionic.Zip.ZipFile zf = Ionic.Zip.ZipFile.Read(zipPath))
{
zf.ExtractAll(appPath);
}
While you can't specify it for a specific call to Extract() or ExtractAll(), the ZipFile class has a FlattenFoldersOnExtract field. When set to true, it flattens all the extracted files into one folder:
var flattenFoldersOnExtract = zip.FlattenFoldersOnExtract;
zip.FlattenFoldersOnExtract = true;
zip.ExtractAll();
zip.FlattenFoldersOnExtract = flattenFoldersOnExtract;
You'll need to remove the directory part of the filename just prior to unzipping...
using (var zf = Ionic.Zip.ZipFile.Read(zipPath))
{
zf.ToList().ForEach(entry =>
{
entry.FileName = System.IO.Path.GetFileName(entry.FileName);
entry.Extract(appPath);
});
}
You can use the overload that takes a stream as a parameter. In this way you have full control of path where the files will be extracted to.
Example:
using (ZipFile zip = new ZipFile(ZipPath))
{
foreach (ZipEntry e in zip)
{
string newPath = Path.Combine(FolderToExtractTo, e.FileName);
if (e.IsDirectory)
{
Directory.CreateDirectory(newPath);
}
else
{
using (FileStream stream = new FileStream(newPath, FileMode.Create))
e.Extract(stream);
}
}
}
That will fail if there are 2 files with equal filenames. For example
files\additionalfiles\file1.txt
temp\file1.txt
First file will be renamed to file1.txt in the zip file and when the second file is trying to be renamed an exception is thrown saying that an item with the same key already exists

Categories

Resources