Set unicode encoding on all files in folder with c# - c#

I have this folder with a bunch of csv files, that I want to import into SQL Server. That works fine with BULK INSERT.
However I have a problem with the encoding, getting weird charters in the db - if I open the csv files in notepad, and save them again as unicode, it works perfect.
Is their a way in C# to programmaticly, convert all files in a folder to unicode?
Thanks

For all files:
string text = File.ReadAllText("data.txt", Encoding.ASCII);
File.WriteAllText("data.txt", text, Encoding.Unicode);

To expand on #Sandre's answer, you can bulk this operation like this:
var di = new DirectoryInfo(#"path\to\csvFolder");
var csvFiles = di.EnumerateFiles("*.csv", SearchOption.TopDirectoryOnly);
var outputFolderDi = new DirectoryInfo(Path.Combine(di.FullName, "outputFolder"));
outputFolderDi.Create();
foreach(var filePath in csvFiles.Select(fi => fi.FullName))
{
var text = File.ReadAllText(filePath);
var fileName = Path.GetFileName(filePath);
var newFilePath = Path.Combine(outputFolderDi.FullName, fileName);
File.WriteAllText(newFilePath, text, Encoding.Unicode);
}
I make no guarantee that this code is correct. Please check carefully before deploying on your file system!

Related

Get the filename of a file that was created through ZipFile.ExtractToDirectory()

string zipPath = #"D:\books\"+fileinfo.DccFileName;
string extractPath = #"D:\books";
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
This is a simple piece of code that does exactly what i want it to do: Gets a zip file from d:\books and unzips it into the same directory. Is there any way i can read the filename of the newly created file (considering that there is only one file in the .zip archive). I would prefer a solution that does not involve reading changes in the directory since other files might be created in it at the same time of the unzip.
You can construct the path by inspecting the archive
var intentedPath = string.Empty;
//open archive
using (var archive = ZipFile.OpenRead(zipPath)) {
//since there is only one entry grab the first
var entry = archive.Entries.First();
//the relative path of the entry in the zip archive
var fileName = entry.FullName;
//intended path once extracted would be
intentedPath = Path.Combine(extractPath, fileName);
}

How to open PowerPoint file in resource file C#

I have a number of small PowerPoint files in my resources folder and I want to open them. I'm having issues doing this as my Resource.sendToPPTTemp is of type byte[] and to open the file I need it as a string. Is there a way I can open a file from resources as a string?
var file = Resources.sendToPPTTemp;
ppnt.Application ppntApplication = new ppnt.Application();
var _assembly = Assembly.GetExecutingAssembly();
var myppnt = ppntApplication.Presentations.Open(file.ToString());
ppntApplication.Visible = MsoTriState.msoTrue;
You need to give the path to your file to the Open method, not the binary representation. Either you have the path and pass it to the method or you have to create a file with your byte[].
I'd rather create a folder with all your PPT and store in your resource file the path to that folder. Then you can use the first method:
var di = new DirectoryInfo(Resources.PPTFolderPath);
foreach(var file in di.GetFiles())
{
var myppnt = ppntApplication.Presentations.Open(fi.FullName);
ppntApplication.Visible = MsoTriState.msoTrue;
[..]
}
But if you really want to store your PPT in the resource file, you can do it like this, with a temporary file for example:
var tmpPath = Path.GetTempFileName();
try
{
File.WriteAllBytes(tmpPath, Resources.sendToPPTTemp);
var myppnt = ppntApplication.Presentations.Open(tmpPath);
ppntApplication.Visible = MsoTriState.msoTrue;
[..]
}
finally
{
// you have to delete your tmp file at the end!!!
// probably not the better way to do it because I guess the program does not block on Open.
// Better store the file path into a list and delete later.
var fi = new FileInfo(tmpPath);
fi.Delete();
}

How can I write and read a text doucument in a folder?

string curetn = Environment.CurrentDirectory;
string path = curetn.ToString() + #"\DATA\SaveGame.txt";
Console.WriteLine(path);
TextReader tr = new StreamReader(path);
Hello, I am making a text-adventure, and I do not like having all my save files, and mp3 file in the same place as my application. I would like for the files to be in a folder. I want to be able to use StreamWriter and StreamReader, to be able to write and read files that are in a folder. This file is also in a distributable folder, not just in the Visual Studios Projects folders. I have tried everything I can, and this is what I have. I also have one of these for StreamWriter. Please help!
Edit:
The thing that does not work, is that it does not read the lines, and assigns them to a variable. I have it in a try-catch, and it catches, and displays the error message that I wrote.
If you are looking for simply read and write lines from file you can try this
using (StreamReader sr = new StreamReader(path))
{
while (!sr.EndOfStream)
{
sr.ReadLine();
}
}
string s;
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(s);
}
So basically what you want to do is read the text file:
string data[] = File.ReadAllLines(path); // Read the text file.
var x = data[1]; // Replace the '1' with the line number you want.
Console.WriteLine(x);
This is a good way to read the text file, I think it's better than opening a stream.
You can also write to it, so every time you want to save, just do this:
// When you want to write:
File.WriteAllText(path, "");
File.AppendAllText(path, "Add a data line" + Environment.NewLine); // Environment.NewLine adds a line.
Keep appending text to the file for the data you need.

Copy a specific file (.docx, .pdf, .pptx etc) form folder in C#

I am trying to copy a file (.docx, .pdf, .pptx etc) from a source folder(on server) to a destination folder(on client).
The user can choose which among the list of files that he wants to download. He selects the files and then downloads it(Copies it to his computer) to the destination path
dstnLocation= #"C:\Fldr\Docs;
My Code:
string sourceLocation = textBox2.Text;
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
file.Directory.Create();
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
The problem is that it creates a file as "Docs"(where one has to use open with to open the file) and if I am not wrong then its because of the destination path. Could someone please tell what all am I doing wrong.
The source path is retrieved through database!
you need to concat otherwise you're destination location is just the folder not the file path destination
so do something like
var destFile = string.Format(#"{0}\{1}", dstnLocation, Path.GetFileName(sourceLocation));
then copy that
So code becomes
string sourceLocation = textBox2.Text;
string dstnLocation = string.Format(#"C:\Fldr\Docs\{0}", Path.GetFileName(sourceLocation);
if (! System.IO.Directory.Exists(dstnLocation))
{
System.IO.Directory.CreateDirectory(dstnLocation);
}
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
You are creating the file name incorrectly:
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
This creates a file with the name "C:\Fldr\Docs" for example what you want is "C:\Fldr\Docs\myfilename.docx" if I am not mistaken?
Try this instead:
var filename = Path.GetFileName(sourceLocation);
string dstnLocation = Path.Combine(#"C:\Fldr\Docs", filename);
The problem here is that the destination requires an "output" file name.
This problem lies in this line of code
System.IO.File.Copy(sourceLocation, dstnLocation,true);
The dstnLocation needs to be concatenated with the output file name for example:
System.IO.File.Copy(sourceLocation, Path.Combine(dstnLocation,"Database.dbs"),true);

Use content of FileUpload

I am attempting to add a file import function to an admin webpage where a CSV file will be imported from a local C: drive
I've just realized that string filePath = Path.GetFileName(FileUpload1.FileName); doesn't actually allow the client path to be read and only gives the filename.
protected void btnImportData_Click(object sender, EventArgs e)
{
List<CSVFile> entries = new List<CSVFile>();
string filePath = Path.GetFileName(FileUpload1.FileName);
using (TextFieldParser parser = new TextFieldParser(filePath))
{
//Other code
}
}
Currently the line TextFieldParser parser = new TextFieldParser(filePath) gives an error as I can't get the full path to the CSV.
Is it possible to load the contents of FileUpload1 into variable parser instead? I can see the control has content but not sure how or if it's possible?
The FileName property is simply the filename the browser sent, and is not yet physically stored on the server. To do so, you'll need to save it first:
string filePath = String.Format({0}{1}", System.IO.Path.GetTempPath(), FileUpload1.FileName); // Save to temp directory
FileUpload1.SaveAs(filePath);
using (TextFieldParser parser = new TextFieldParser(filePath))
{
//...
}
File.Delete(filePath); // Delete the file if you're done with it
Also, if TextFieldParser can take in a System.IO.Stream, you won't even need to save the file to disk first:
using (TextFieldParser parser = new TextFieldParser(FileUpload1.FileContent)) // Read stream
{
//...
}
Take into account that the file is not stored yet on the server so there is no path. FileName is just that: a file name and not a full path.
If you require the file to exist on the file system in order to parse it, you'll need to first save it.

Categories