I have a problem with System.IO.Path.GetFileNameWithoutExtension. If i load a file, the string which is returned by the method contains some hidden chars. In HEX: 3F.
The follwing pictures contains the problem. See the hex editor:
The texfiles were created with Notepad++ and the Encoding is UTF-8 without BOM.
Maybe some one has a solution, thank you!
I created file with Notepad++ v6.6.4 and put the file in debug folder called myFile.txt and the Encoding is "UTF-8 without BOM" and if you apply the next code which read all the text from the original file created above and put all the content in new file in the same directory you will find exactly all the content without any difference.
using System;
using System.IO;
namespace FilePathWithNotepad__
{
class Program
{
static void Main(string[] args)
{
string originalFilePath = Environment.CurrentDirectory + "\\myFile.txt";
string title = Path.GetFileNameWithoutExtension(originalFilePath);
string content = File.ReadAllText(originalFilePath);
string newfile = Path.GetFileName(Environment.CurrentDirectory + "\\new.txt");
File.WriteAllText(newfile,content);
}
}
}
Related
While learning with books sometimes i copy some code from pdf, to test it.
This tiny exe was suppose to change ‘ ’ “ ” to ' or "
and it work fine, but only if tested *.cs file is opened manually before I debug my methods.
Otherwise it's not working. When code paste into concerned file directly, and closed, without opening once again The Replace method return "Unexpected character ?"
I dont understand the probleme, since File.ReadAllText already open and close the file.
using System;
using System.Collections.Generic;
using System.IO;
class Test
{
public static void Main()
{
string path = Directory.GetCurrentDirectory();
string[] csfiles = Directory.GetFiles(path, "*.cs");
foreach (var item in csfiles)
{
string text = File.ReadAllText(item);
text = text.Replace("‘", "\'")
.Replace("’", "\'")
.Replace("“", "\"")
.Replace("”", "\"");
File.WriteAllText(item, text);
}
}
}
Apparently File.ReadAllText(); does change encoding when opening.
My caracters (being in ASCII+ANSI) was ruined just when opened.
string text = File.ReadAllText(path, Encoding.Default); keeps original encoding when opening. Replace work fine on this, and so my exe.
:) Thank you for your help!
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = Directory.GetCurrentDirectory();
string[] csfiles = Directory.GetFiles(path, "*.cs");
foreach (var item in csfiles)
{
string text = File.ReadAllText(item, Encoding.Default);
string newtext = text.Replace("‘", "\'")
.Replace("’", "\'")
.Replace("“", "\"")
.Replace("”", "\"");
File.WriteAllText(item, newtext);
}
}
}
How to read an ANSI encoded file containing special characters
I must download a file using SSH.NET library. After I download a file I must delete the remote file.
Everything works but the file name is encoded. I mean that for example, if I have a file named New file, I download/upload a file named New%20file. Now, if I download/upload the new file I obtain New%25%20file and again New%252520file... and so on...
This is very problematic. How can I avoid to change the file name after I download it?
Here the code I am using to download:
string fileName = base.Uri.GetFileName();
string fullPath = Path.Combine(pathFolder, fileName);
using (SftpClient client = new SftpClient(
new PasswordConnectionInfo(
base.Uri.Host, SftpFlowGateway.CONST_PORT_NUMBER,
base.Credential.UserName,
base.Credential.Password))
)
{
client.Connect();
using (FileStream fileStreamToDownload = new FileStream(fullPath, FileMode.Create))
{
client.DownloadFile(base.Uri.LocalPath, fileStreamToDownload);
}
client.Disconnect();
}
EDIT:
base.Uri is just defined as follow:
private Uri _uri;
public Uri Uri
{
get { return _uri; }
protected set { _uri = value; }
}
And the GetFileName method is:
public static string GetFileName(this Uri path)
{
return path.Segments.Last();
}
When I debug, I can see that the properties of the class Uri have the correct value... It is not encoded
Thank you
You are passing a stream you have created yourself (new FileStream) to the SSH.NET. The library does not even know it's a file it is writing to, nor its name. So it's not the library that URL-encodes the file name. It has to be URL-encoded in the fullPath variable already.
It's the Uri.AbsolutePath and Uri.Segments that return URL-encoded path. That's how the System.Uri class works. I assume you use the constructor overload Uri(string uriString).
Use the static method Uri.UnescapeDataString to reverse encoding done by the Uri constructor.
Note the obsoleted constructor overload Uri(string uriString, bool dontEscape).
It looks like the SSH.Net library simply URL encodes the file names.
I suppose you could rename the file after you've downloaded it using the System.Web.UrlDecode method?
Or UrlEncode the filename when you upload.
Unfortunately, I haven't used the library myself but you could help further by letting us know if the name change occurs on download or upload or both.
EDIT:
As martin mentioned, its not the library doing any encoding.
I've just tried it myself.
string fileName = "file with spaces.txt";
using (Stream outputFile = File.OpenWrite(localDir + "\\" + fileName))
{
sftpClient.DownloadFile(fileName, outputFile);
}
The created file is also named "file with spaces.txt" though that would've been the case anyway since it was created via the stream.
I want to launch my soft directly by open a file with a specific extension (here no problem) but I was wondering how read directly the content of this file ?
I checked on internet but nothing useful came out.
Thanks
Try to use the File class, in particular the File.ReadAllText Method
Sample MSDN usage
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
In order to read the file name from the command line (invoked on double click)
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main(string[] args)
{
Console.Writeline("I bet your filename is: {0}", args[0]);
}
}
See also this very nice example.
File.ReadAllLines is waht your looking for, you should provide an Serilizer to get your spezific data from that file.
But what do you want do read from that file? if it is an executable i think you don't want to read that file or?
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; }
}
I'm using System.Diagnostics.Process.Start("my.exe"); to call an exe
Now that I can call my .exe, I want to bind/merge it into my c# application so that when I build my application, I can get the exe built inside the projectName\Debug\builtProgram.exe or any other way to finally get a single exe file with my desired exe file inside it.
For example, consider I create a program A and I want it to encase it inside another program B which contains only one button 'Launch Program A'. And let's say program B is portable - with a single exe file.
Question is - How to create program B?
You can include the .exe as an embedded resource in your .NET assembly, and then dump it to disk to a temporary file on startup:
var thisAssembly = Assembly.GetExecutingAssembly();
var executableFileName = Path.GetTempFileName();
using(resourceStream = thisAssembly.GetManifestResourceStream("name.of.resource.exe"))
using(fileStream = File.Create(executableFileName))
{
resourceStream.CopyTo(fileStream);
}
Then you call it just like you would normally.
Process.Start(executableFileName);
Since it's hard for me to extract embedded resource.
Here's my answer:
public static void getbytez(string file, string outp)
{
byte[] buffer = File.ReadAllBytes(file);
string base64Encoded = Convert.ToBase64String(buffer);
File.WriteAllText(outp+ ".txt", base64Encoded);
//copy the base64encoded text.
//Code by CursedGmod. credit me please :D
}
public static void extract2idk(string txtfile, string outp, string exten)
{
byte[] gu = Convert.FromBase64String(txtfile);
// use it like this: byte[] gu = Convert.FromBase64String(your base64 converted text that you copied from the txt file);
// or use File.ReadAllText if you're making a stub builder.
File.WriteAllBytes(outp + exten, gu);
Process.Start(Environment.ExpandEnvironmentVariables("%TEMP%") + Path.GetFileName(txtfile));
}