This code works as expected in .net framework but not in .net core 2
The file in.txt contains "Düsseldorf"
in .net framework the output is "Düsseldorf"
in .net core the output is "D�sseldorf"
(I've tried all the other Encodings out of desperation already... no one works)
string infile = #"C:\in.txt", outFile = #"C:\out.txt";
var inStr = new StreamReader(infile, Encoding.Default);
var outStr = new StreamWriter(outFile, false, Encoding.Default);
while (!inStr.EndOfStream)
{
outStr.WriteLine(inStr.ReadLine());
}
outStr.Flush();
inStr.Dispose();
outStr.Dispose();
Any Ideas why it's not working?
According to the official MSDN page the default encoding is not fixed - it depends on the OS settings. If you know which encoding the file has, specify it!
EDIT:
Then try print the encoding details (like name) from the .net framework one that works. Then specify the same in .net core 2. Do not rely on the default one. This page MSDN, List of encodings in the code sample contains a list of encodings that are supported.
UPDATE by gsharp:
I had to reference the NuGet Package System.Text.Encoding.CodePages, register them and use it
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var enc1252 = Encoding.GetEncoding(1252);
var inStr = new StreamReader(infile, enc1252);
var outStr = new StreamWriter(outFile, false, enc1252);
Related
In ASP .NET Core, I am trying to add some XML-Element with attributes to an existing XML file.
In ASP NET 4.5, I would have used the code below to make this working:
string path = Server.MapPath("~/Data/foo.xml");
XDocument xdoc = XDocument.Load(path);
//Do stuff with XElement and XAttributes...
xdoc.Save(path);
But with ASP .NET Core, I cannot use Server.MapPath(), So I get the complete path with IHostingEnvironment instead: (Read more here )
Running the complete code below on ASP .NET Core will result in "Cannot convert from String to System.IO.Stream" when trying to run "xdoc.Save(pathToDataFile);" ??
var contentRoot = hostingEnvironment.ContentRootPath;
string pathToDataFile = contentRoot + "\\Data\\foo.xml";
XDocument xdoc = XDocument.Load(pathToDataFile);
//Do stuff with XElement and XAttributes...
xdoc.Save(pathToDataFile);
Why is "xdoc.Save()" not working in ASP .NET Core but working fine in .NET 4.5?
APIs available in .NET Core are a subset of the ones available in the full .NET framework. In some areas, you'll find that pretty much everything from .NET 4.5 is available in .NET Core, but that's not always the case.
In your case, if you have a look with Visual Studio at what overloads of the Save method are available, you'll find these ones:
public void Save(Stream stream);
public void Save(TextWriter textWriter);
public void Save(XmlWriter writer);
public void Save(Stream stream, SaveOptions options);
public void Save(TextWriter textWriter, SaveOptions options);
The reason why you have a compilation error is now pretty clear. In .NET Core, there's no overload accepting a string that defines the file path where the document should be saved.
You'll have to create a write-enabled Stream pointing to the desired path first and pass that Stream to the Save method. You can have a look at the full .NET framework implementation for reference.
I had the same issue, and FileStream works for me.
FileStream fileStream = new FileStream("file.xml", FileMode.Create);
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true};
XmlWriter writer = XmlWriter.Create(fileStream, settings);
Remember to use the following lines of code to prevent the file from being truncated.
writer.Flush();
fileStream.Flush();
i know this question is asked 1000 times but I don't want to use any external tools like (DotNetZip or SharpZipLib).
I have currently this working piece of code:
string _from = Path.Combine(apk, "*.*") + '\0';
string _to = destination + '\0' + Path.Combine(destination, "*.*") + '\0';
NativeMethods.SHFILEOPSTRUCT fileop = new NativeMethods.SHFILEOPSTRUCT();
fileop.pFrom = _from;
fileop.pTo = _to;
fileop.wFunc = NativeMethods.FO_Type.FO_COPY;
fileop.fFlags = NativeMethods.FOF_Flag.FOF_WANTNUKEWARNING;
NativeMethods.SHFileOperation(ref fileop);
My problem is that I can't extract/copy a single file/folder. If i replace the *.* for example with res\\drawable\\icon.png it will do nothing.
Can someone tell me how to extract a single file/folder using the SHFILEOPSTRUCT? Do I miss something?
The code supports:
Framework Version: .Net Client 4
OS: WinXP, 8, 8.1, 10
EDIT (Notice):
When you use this piece of code in an C# thread you'll always get an 'Path length exceeded' error... In this case you need to use an 'Dispatcher'.
.NET 4.5 has native ZIP support, you should try that
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
foreach (ZipArchiveEntry entry in archive.Entries.Where(e => e.FullName.Contains("a")))
{
entry.ExtractToFile(Path.Combine(extractPath, entry.FullName));
}
}
SHFileOperation is not capable of extracting individual items from a ZIP file. You options as I see them are:
Include a 3rd party ZIP library.
Switch to .net 4.5 and use the framework supplied ZIP library.
See if ZipPackage from System.IO.Packaging has enough functionality to meet your needs.
Write your own ZIP code.
Extract the entire ZIP file to a temporary directory and then pick out the parts you need.
pFrom needs to be double null-terminated:
string _from = Path.Combine(apk, "*.*") + "\0\0";
This is because it can contain multiple paths, which should be null-separated.
I have to use StringBuilder instead of a List of strings because of being stuck with .NET 1.1 for this project.
I want to write a series of debug messages I've written to a file to study at my leisure, as there is too much to see on the screen (the MessageBox doesn't have scrollbars). Some of the easy ways to write a file don't seem to be available in .NET 1.1. I also don't have access to Environment.Newline to cleanly separate the lines I append (AppendLine is not available in this archaic version of StringBuilder, either).
What is the easiest way in .NET 1.1 (C#) to write out the contents of the StringBuilder to a file? There is no "C" drive on the handheld device, so I reckon I will have to write it to "\hereIAm.txt" or something.
You still have access to StreamWriter:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"\hereIam.txt"))
{
file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}
From the MSDN documentation: Writing to a Text File (Visual C#).
For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText method.
System.IO.File.WriteAllText(#"C:\TextFile.txt", stringBuilder.ToString());
I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.
In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.
System.IO.File.WriteAllText(#"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());
No need for a StringBuilder:
string path = #"c:\hereIAm.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Here");
sw.WriteLine("I");
sw.WriteLine("am.");
}
}
But of course you can use the StringBuilder to create all lines and write them to the file at once.
sw.Write(stringBuilder.ToString());
StreamWriter.Write Method (String) (.NET Framework 1.1)
Writing Text to a File (.NET Framework 1.1)
StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:
StringBuilder sb = new StringBuilder();
sb.Append(......);
StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
sw.Write(sb.ToString());
sw.Close();
Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.
If you need to write line by line from string builder
StringBuilder sb = new StringBuilder();
sb.AppendLine("New Line!");
using (var sw = new StreamWriter(#"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}
If you need to write all text as single line from string builder
StringBuilder sb = new StringBuilder();
sb.Append("New Text line!");
using (var sw = new StreamWriter(#"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}
I am using IKVM to port some java libraries into my c# project. The library api (StanfordNLP) requires that a file be loaded to train the statistical models used by the nlp functions. Loading the file from the file system has worked well for weeks, but I would now like to add the file as an embedded resource in a dll, rather than retrieving it from the file system.
The problem is that the java api is not finding the .net embedded resource.
Here is a snippet of code that works when retrieving a file from the file system:
public class SNLPModel
{
public LexicalizedParser LP;
public SNLPModel()
{
// Using a relative file path in the target build directory
LP = LexicalizedParser.loadModel("models-stanford\\englishPCFG.ser.gz");
}
}
But when I make the "englishPCFG.ser.gz" file an embedded resource in visual studio (using VS2012), and change the code to match:
public class SNLPModel
{
public LexicalizedParser LP;
public SNLPModel()
{
// Using this line of code to verify that the file is being loaded as
// an embedded resource. Running in debug, I have verified that it is, and
// noted its complete name.
string[] s = System.Reflection.Assembly.GetExecutingAssembly()
.GetManifestResourceNames();
java.io.InputStream modelFile = java.lang.ClassLoader
.getSystemResourceAsStream
("FeatureExtraction.StanfordNLP_Models.englishPCFG.ser.gz");
java.io.ObjectInputStream x = new java.io.ObjectInputStream(modelFile);
LP = LexicalizedParser.loadModel(x);
}
}
the InputStream object, modelFile, is always returned null. I have tried various forms of the resource string, replaceing the first two dots (".") with forward slash ("/"), backslash ("\") and double backslash ("\\"). I am beginning to suspect that java.io cannot access the .net resource. It would not be surprising that the java api does not recognize the .net resources, but I thought IKVM might provide a bridge. I have seen a reference to something called IKVM.Internals.VirtualFileSystem, but only the one reference (http://old.nabble.com/Manual-by-name-embedded-resource-lookup--td31162421.html) and haven't found any IKVM dlls that actually contain the class.
Any help would be much appreciated. I am using:
c#.NET 4.5
Visual Studio 2012
Latest Stanford NLP java libraries
IKVM 7.0.4335.0
There is no automatic support for this in IKVM, but it is really easy to do it yourself:
var asm = Assembly.GetExecutingAssembly();
var stream = asm.GetManifestResourceStream("FeatureExtraction.StanfordNLP_Models.englishPCFG.ser.gz");
var inp = new ikvm.io.InputStreamWrapper(stream);
var x = new java.io.ObjectInputStream(inp);
The hint to the right solution is in the extension of the file that you embed.
If it is plain serialized java object (like english-left3words-distsim.tagger) you can load it like this
let model = "../english-left3words-distsim.tagger"
use fs = new FileStream(model, FileMode.Open)
use isw = new ikvm.io.InputStreamWrapper(fs)
let tagger = edu.stanford.nlp.tagger.maxent.MaxentTagger(isw)
but if your model has extension .gz this mean that file is gzipped, and you have to wrap input stream into java.util.zip.GZIPInputStream before deserialization
let model = "../englishRNN.ser.gz"
use fs = new FileStream(model, FileMode.Open)
use isw = new ikvm.io.InputStreamWrapper(fs)
use ois =
if model.EndsWith(".gz")
then
let gzs = new java.util.zip.GZIPInputStream(isw)
new java.io.ObjectInputStream(gzs)
else new java.io.ObjectInputStream(isw)
let lp = edu.stanford.nlp.parser.lexparser.LexicalizedParser.loadModel(ois)
well i am using all these codes:
// StreamWriter file = new StreamWriter(AppSettings.Instance.Dpath + "\\notaventa.txt");
// StreamWriter file = new StreamWriter(AppSettings.Instance.Dpath + "\\notaventa.txt", false, System.Text.Encoding.GetEncoding(1252));
' Dim objEscritor = New StreamWriter("C:\temp\salida_encoding.txt", True, System.Text.Encoding.Default)
// StreamWriter file = new StreamWriter(AppSettings.Instance.Dpath + "\\notaventa.txt", true, System.Text.Encoding.ASCII);
but none work for print
canción
everyone print
canci?n
how can i fix it? i am using
compact framework 3.5
for Hand helds
You can fix it by not specifying Encoding.ASCII. UTF-8 is usually a good bet, although of course it depends on what's going to read the file. Basically ASCII doesn't have any accented characters; it stops at U+007E.
I'd expect Encoding.GetEncoding(1252) to work though, as Windows 1252 contains character "ó". Ditto the default when you don't specify an encoding, as that would use UTF-8. Are you sure your string contains the right data to start with? What are you using to read the file, too?
ASCII does not include support for the ó character. Unless you have compelling reason otherwise, you should always use Unicode:
System.IO.StreamWriter file = new System.IO.StreamWriter(
Path.Combine(AppSettings.Instance.Dpath, "notaventa.txt"), true,
System.Text.Encoding.UTF8);
Unrelated to your question: You should use Path.Combine (rather than explicit string concatenation) for constructing file paths. It would save you the headache of determining whether to include the leading/trailing \ or not.