I have a few reports that are exported to Excel. The problem is whereever there are special characters, it is being replaced by some funny symbols
For example, '-'(hyphen) was replaced by –...
Any help to solve the problem??
The most straight forward way is to encode the text file as UTF-8. I ran the following code, opened the resulting hyphen.txt file in Excel 2007 and it worked as expected:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var hyphen = "\u2010\r\n";
var encoding = Encoding.UTF8;
var bytes = encoding.GetBytes(hyphen);
using (var stream = new System.IO.FileStream(#"c:\tmp\hyphen.txt", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
{
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
This is the code -- view at PasteBin.
Related
I am trying to download HTML webpage locally to my computer and this works fine, however, it is a Bulgarian article and it does not seem to display properly afterwards.
I have tried many encoding (Code Page Identifiers - WINDOWS-1251, UTF-8, etc.) from MSDN https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx but for some reason I cannot get it to open as intended.
For example:
Стара планина - величествената кръстница на Балканския полуостров
Displays as:
??N�?�N�?� ???�?�???????� - ???�?�??N�?�N?N�???�???�N�?� ??N�NSN?N�????N�?� ???� ?�?�?�???�??N?????N? ?????�N???N?N�N�????
Below I am posting my simple code. Your help will be much appreciated! :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace pageDownloader
{
class Program
{
public static void DownloadPage()
{
WebClient client = new WebClient();
string webpage = client.DownloadString("http://www.nasamnatam.com/statia/Stara_planina_velichestvenata_krystnica_na_Balkanskiia_poluostrov-2525.html");
System.IO.File.WriteAllText(#"C:\test\downloadedpage.html", webpage, Encoding.GetEncoding("windows-1251"));
}
static void Main()
{
DownloadPage();
}
}
}
Console.OutputEncoding = Encoding.UTF8;
string htmlCode = "";
WebClient client = new WebClient { Encoding = Encoding.UTF8 };
byte[] reply = client.DownloadData($"http://www.nasamnatam.com/statia/Stara_planina_velichestvenata_krystnica_na_Balkanskiia_poluostrov-2525.html");
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding encoding1251 = Encoding.GetEncoding("windows-1251");
var convertedBytes = Encoding.Convert(encoding1251, Encoding.UTF8, reply);
htmlCode = Encoding.UTF8.GetString(convertedBytes);
I am trying to read a file into a string which then I will send to another application.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:\text.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I am getting the error:
The file could not be read:
Could not find file 'c:\users\andymarkmn\documents\visual studio 2015\Projects\FileApplication\FileApplication\bin\Debug\text.txt'.
I have tried putting the file in bin debug folders as well.
How to make sure the code works ?
EDIT: As suggested, I tried using the different ways.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string filepath = "c:\\text.txt";
try
{
string lines = File.ReadAllText(filepath);
Console.Write(lines);
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I still get the error:
The file could not be read:
Could not find file 'c:\text.txt'.
You have accidentally used an unwanted escape sequence in your filename string.
new StreamReader("c:\text.txt")
should be
new StreamReader(#"c:\text.txt")
Otherwise \ gets treated as an escape character, at \t is a tab character. This leaves an unexpected result, and the wrong path for the file.
# instructs the compiler to ignore any escape characters in the string.
"c:\text.txt" will not work as \ is an escape character.
use #"c:\text.txt" or "c:\\text.txt"
When StreamReader is given a non-qualified path as a parameter, it will look for the file in the application's working directory as you have done:
using (StreamReader sr = new StreamReader("c:\text.txt"))
If the file isn't located there, probably you should give StreamReader a fully qualified path:
using (StreamReader sr = new StreamReader(#"c:\text.txt"))
//or...
using (StreamReader sr = new StreamReader("c:\\text.txt"))
Try:
using (StreamReader sr = new StreamReader(#"C:\text.txt"))
If you use c:\text, C# considers that the string has a tabulador between C: and text.txt.
I'm looking at removing a large section of bytes from within a file and then inserting a new large section of bytes starting in the same place the original removed bytes did, all using C#. Does anyone know how to go about this? I can't see to find any help online.
Any help would be much appreciated!
Thanks.
This should get you started.
Steps are as follow:
Find a position you want to edit.
Prepare your new data
Write
.
using System;
using System.Text;
using System.IO;
namespace Test
{
class Program
{
static void Main(string[] args)
{
using (BinaryWriter writer = new BinaryWriter(File.Open("TextFile1.txt", FileMode.Open, FileAccess.ReadWrite)))
{
int offset = 1; //position you want to start editing
byte[] new_data = new byte[] { 0x68, 0x69 }; //new data
writer.Seek(offset, SeekOrigin.Begin); //move your cursor to the position
writer.Write(new_data);//write it
}
}
}
}
I want to make a program that searches a file for desired chars in words (letters č ć ž š), replaces them with c z s etc. and saves the file. In my attempt, however, I get some stupid signs, so that means it opens the file wrongly. When I try to add encoding.unicode it gives me errors (shown below). And one more question, how do I make a program which opens files by dragging them in an .exe file.
Error 3 The best overloaded method match for
'System.IO.File.Open(string, System.IO.FileMode,
System.IO.FileAccess)' has some invalid
arguments C:\Users\Vulisha\AppData\Local\Temporary
Projects\ConsoleApplication1\Program.cs 14 59 ConsoleApplication1
Error 4 Argument '3': cannot convert from 'System.Text.Encoding' to
'System.IO.FileAccess' C:\Users\Vulisha\AppData\Local\Temporary
Projects\ConsoleApplication1\Program.cs 14 122 ConsoleApplication1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (StreamReader stream = new StreamReader(File.Open(#"C:\Users\Vulisha\Desktop\titl.txt", FileMode.Open)))
{
string fileText = stream.ReadToEnd();
// Do your replacements
fileText = fileText.Replace(#"č", #"c");
fileText = fileText.Replace(#"ć", #"c");
fileText = fileText.Replace(#"š", #"s");
fileText = fileText.Replace(#"ž", #"z");
fileText = fileText.Replace(#"đ", #"d");
fileText = fileText.Replace(#"Č", #"C");
fileText = fileText.Replace(#"Č", #"C");
fileText = fileText.Replace(#"Š", #"S");
fileText = fileText.Replace(#"Ž", #"Z");
fileText = fileText.Replace(#"Đ", #"D");
using (StreamWriter writer = new StreamWriter(File.Open(#"titl.txt", FileMode.Create)))
{
// You do a create because the new file will have less characters than the old one
writer.Write(fileText);
}
}
}
}
}
You need to be more careful with placement of parentheses. You need
new StreamWriter(File.Open(#"titl.txt", FileMode.Create), Encoding.Unicode)
but you wrote
new StreamWriter(File.Open(#"titl.txt", FileMode.Create, Encoding.Unicode))
See the difference?
I'm trying to hash a file using SHA1. The result looks like this: B7-DB-B9-93-E7-2F-6F-EB-6D-CD-CC-A8-DE-D2-F1-01-6E-8A-53-BC
How to I replace dashes to empty string or just remove them?
The code trying to replace the dashes, but it seems like it don't change anything and dashes are still in place.
using (HashAlgorithm hashSHA1 = new SHA1Managed())
using (Stream file = new FileStream(ofdBrowse.FileName, FileMode.Open, FileAccess.Read))
{
byte[] hash = hashSHA1.ComputeHash(file);
txtSHA1.Text = BitConverter.ToString(hash).Replace("-", "");
}
Difference between dash and hyphen?
http://msdn.microsoft.com/en-us/library/3a733s97.aspx
Not really sure. Just my guess in the dark.
The code you've give definitely removes the dashes. Short but complete program to demonstrate that:
using System;
using System.IO;
using System.Security.Cryptography;
class Test
{
static void Main(string[] args)
{
using (HashAlgorithm hashSHA1 = new SHA1Managed())
{
// Actual data doesn't matter
using (Stream data = new MemoryStream())
{
byte[] hash = hashSHA1.ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", ""));
}
}
}
}
So, potential cause of your problem:
You're not running the build you think you are
You've got other code which does the hashing but doesn't have the Replace call
You're looking at the wrong bit of the UI :)
It's hard to really guess which of those (or anything else) is the problem, but that code isn't it...