473,809 Members | 2,722 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert a Widestring to an Ascii String?

Hello dear,

I have a string and every second char is a \0. Can I somehow convert it to a
normal string. Or may-be in the underlying code I am doing something wrong,
choose the wrong C# type?

This is my function I am trying to get right:

public static bool GetPrivateProfi leSectionAsCS(s tring appName, string
fileName, out string section)
{
section = null;
if (!System.IO.Fil e.Exists(fileNa me))
return false;
uint MAX_BUFFER = 32767;
IntPtr pReturnedString = Marshal.AllocCo TaskMem((int)MA X_BUFFER);
uint bytesReturned = GetPrivateProfi leSectionW(appN ame, pReturnedString ,
MAX_BUFFER, fileName);
if ((bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
return false;
System.Text.Str ingBuilder returnedString = new
System.Text.Str ingBuilder((int )bytesReturned) ;
//bytesReturned -1 to remove trailing \0
for (int i = 0; i < bytesReturned - 1; i++)
returnedString. Append((char)Ma rshal.ReadByte( new
IntPtr((uint)pR eturnedString + (uint)i)));
Marshal.FreeCoT askMem(pReturne dString);
section = returnedString. ToString();
section.Replace ("\0", ""); // this does not work
return true;
}

And this is how my string section looks like:

"N\0U\0M\0B\0E\ 0R\0=\0f\0t\0A\ 0u\0t\0o\0I\0n\ 0c\0\0\0S\0t\0a \0t\0u\0s\0N\0r \0=\0I\0D\0A\0\ 0\0P\0a\0t\0N\0 a\0m\0e\0=\0N\0 o\0t\0U\0s\0e\0 d\0\0\0D\0a\0t\ 0e\0=\0T\0x\0_\ 0D\0t\0T\0m\0<\ 0r\0e\0g\0e\0x\ 0>\0(\00\0[\01\0-\09\0]\0|\0[\01\02\0]\0[\00\0-\09\0]\0|\03\0[\00\01\0]\0)\0-\0(\00\0[\01\0-\09\0]\0|\01\0[\00\01\02\0]\0)\0-\0(\01\09\0|\02 \00\0)\0[\00\0-\09\0]\0[\00\0-\09\0]\0<\0/\0r\0e\0g\0e\0x \0>\0\0\0T\0i\0 m\0e\0=\0T\0x\0 _\0D\0t\0T\0m\0 <\0r\0e\0g\0e\0 x\0>\0[\00\0-\09\0]\0[\00\0-\09\0]\0:\0[\00\0-\09\0]\0[\00\0-\09\0]\0:\0[\00\0-\09\0]\0[\00\0-\09\0]\0<\0/\0r\0e\0g\0e\0x \0>\0\0\0V\0e\0 l\0d\0n\0a\0a\0 m\0=\0F\0i\0e\0 l\0d\0_\0L\0a\0 b\0e\0l\0+\0F\0 i\0e\0l\0d\0_\0 N\0a\0m\0e\0\0\ 0C\0l\0i\0n\0i\ 0c\0=\0T\0s\0t\ 0l\0\0\0B\0e\0a \0m\0N\0r\0=\0N \0o\0t\0U\0s\0e \0d\0\0\0S\0e\0 g\0m\0N\0r\0=\0 N\0o\0t\0U\0s\0 e\0d\0\0\0T\0e\ 0r\0m\0i\0n\0a\ 0t\0e\0=\0N\0o\ 0t\0U\0s\0e\0d\ 0\0\0D\0i\0a\0p \0h\0P\0r\0e\0s \0c\0=\0N\0o"
Nov 16 '07 #1
5 9068
On Nov 16, 12:34 pm, "Marc" <i...@ingcarlea se.nlwrote:
I have a string and every second char is a \0. Can I somehow convert it to a
normal string. Or may-be in the underlying code I am doing something wrong,
choose the wrong C# type?
I don't know the details of GetPrivateProfi leSectionW, but you may
well be able to get away with creating a byte[] instead of using
AllocCoTaskMem to return an IntPtr. You can then pass that byte[] into
GetPrivateProfi leSectionW and use Encoding.Unicod e afterwards.

Otherwise, use Marshal.Copy to copy the data into a byte[], and then
again you can use Encoding.Unicod e to turn the data into a string.

If these don't work, it's worth asking on the .interop newsgroup.

Jon
Nov 16 '07 #2
Or, he could just use a definition of GetPrivateProvi deSection which
would marshal the string correctly. A declaration that uses bytes in the
parameter doesn't do any good.

The declaration should be:

[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
static extern uint GetPrivateProfi leString(
string lpAppName,
string lpKeyName,
string lpDefault,
[In, Out] char[] lpReturnedStrin g,
uint nSize,
string lpFileName);

The use of the char array is to prevent the marshaling layer from not
sending back all of the characters in the string after finding the first
null character.

It makes it a lot easier than allocating the memory and whatnot (which
should have been placed in a try/finally block, in the case of an
exception).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:b3******** *************** ***********@41g 2000hsh.googleg roups.com...
On Nov 16, 12:34 pm, "Marc" <i...@ingcarlea se.nlwrote:
>I have a string and every second char is a \0. Can I somehow convert it
to a
normal string. Or may-be in the underlying code I am doing something
wrong,
choose the wrong C# type?

I don't know the details of GetPrivateProfi leSectionW, but you may
well be able to get away with creating a byte[] instead of using
AllocCoTaskMem to return an IntPtr. You can then pass that byte[] into
GetPrivateProfi leSectionW and use Encoding.Unicod e afterwards.

Otherwise, use Marshal.Copy to copy the data into a byte[], and then
again you can use Encoding.Unicod e to turn the data into a string.

If these don't work, it's worth asking on the .interop newsgroup.

Jon
Nov 16 '07 #3

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote
Or, he could just use a definition of GetPrivateProvi deSection which
would marshal the string correctly. A declaration that uses bytes in the
parameter doesn't do any good.

The declaration should be:

[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
static extern uint GetPrivateProfi leString(
I am using GetPrivateProfi leSECTION not GetPrivateProfi leSTRING

But I guess the defintion should be:

[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
static extern uint GetPrivateProfi leSection(
string lpAppName,
[In, Out] char[] lpReturnedStrin g,
uint nSize,
string lpFileName);

And this I am using in my program:

[DllImport("kern el32.dll", CharSet = CharSet.Auto)]
static extern uint GetPrivateProfi leSectionW(stri ng lpAppName, IntPtr
lpReturnedStrin g, uint nSize, string lpFileName);

public static bool GetPrivateProfi leSectionAsCS(s tring appName, string
fileName, out string section)
{

So there is a difference, but do not ask me now what is correct.

And there is also this little problem. The section is not one null
terminated string but several. This is in MSDN

"The format of the returned keys and values is one or more null-terminated
strings, followed by a final null character. Each string has the following
form: key=string"

I've already used GetPrivateProfi leSTRING, that one was easy. Ok, I will
look into it and thanks for suggestions.
Nov 16 '07 #4
Marc,

Regardless, if you use the character array, then you can parse the
character array, looking for the null characters, and splitting the strings
apart that way.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Marc" <in**@ingcarlea se.nlwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c omwrote
> Or, he could just use a definition of GetPrivateProvi deSection which
would marshal the string correctly. A declaration that uses bytes in the
parameter doesn't do any good.

The declaration should be:

[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
static extern uint GetPrivateProfi leString(

I am using GetPrivateProfi leSECTION not GetPrivateProfi leSTRING

But I guess the defintion should be:

[DllImport("kern el32.dll", CharSet=CharSet .Auto)]
static extern uint GetPrivateProfi leSection(
string lpAppName,
[In, Out] char[] lpReturnedStrin g,
uint nSize,
string lpFileName);

And this I am using in my program:

[DllImport("kern el32.dll", CharSet = CharSet.Auto)]
static extern uint GetPrivateProfi leSectionW(stri ng lpAppName, IntPtr
lpReturnedStrin g, uint nSize, string lpFileName);

public static bool GetPrivateProfi leSectionAsCS(s tring appName, string
fileName, out string section)
{

So there is a difference, but do not ask me now what is correct.

And there is also this little problem. The section is not one null
terminated string but several. This is in MSDN

"The format of the returned keys and values is one or more null-terminated
strings, followed by a final null character. Each string has the following
form: key=string"

I've already used GetPrivateProfi leSTRING, that one was easy. Ok, I will
look into it and thanks for suggestions.
Nov 16 '07 #5

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om>
Marc,

Regardless, if you use the character array, then you can parse the
character array, looking for the null characters, and splitting the
strings apart that way.
Hey thanks, this works:

[DllImport("kern el32.dll", CharSet = CharSet.Auto)]
static extern uint GetPrivateProfi leSection(strin g lpAppName, [In, Out]
char[] lpReturnedStrin g, uint nSize, string lpFileName);
//
public static bool GetPrivateProfi leSectionAsComm aText(string appName,
string fileName, out string section)
{
section = "";
uint MAX_BUFFER = 327670;
char[] sectionchar = new char[MAX_BUFFER];
if (!System.IO.Fil e.Exists(fileNa me))
return false;
uint bytesReturned = GetPrivateProfi leSection(appNa me, sectionchar,
MAX_BUFFER, fileName);
if ((bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
return false;
for (int i = 0; i < bytesReturned; i++)
{
if (sectionchar[i] != (char)0)
section += sectionchar[i];
else
{
if (i != bytesReturned - 1) section += ',';
}
}
return true;
}
>

Nov 19 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
17422
by: Kai Bohli | last post by:
Hi all ! I need to translate a string to Ascii and return a string again. The code below dosen't work for Ascii (Superset) codes above 127. Any help are greatly appreciated. protected internal string StringToAscii(string S) { byte strArray = Encoding.UTF7.GetBytes(S); string NewString = Encoding.UTF7.GetString(strArray);
6
10237
by: Ricardo Quintanilla | last post by:
i have a code that sends data to a socket listening over as400 platform, the socket responds to me as a "byte array". then i need to convert the "byte array" into a string. the problem is that the data converted from the byte array into a string , is not what i expect. example: - the data returned from the socket is (byte array) "Usuario Sin Atribuciones Para Esta Función"
7
66774
by: MilanB | last post by:
Hello How to convert char to int? Thanks
6
12771
by: Allan Ebdrup | last post by:
How do I easily convert a int to a string? Kind Regards, Allan Ebdrup
5
37346
by: Mika M | last post by:
Hi! I've made little code to convert string into hex string... Public ReadOnly Property ToHexString(ByVal text As String) As String Get Dim arrBytes As Integer() = CharsToBytes(text) Dim sb As StringBuilder = New StringBuilder For i As Integer = 0 To arrBytes.Length - 1
4
2827
by: Dirk Hagemann | last post by:
Hi! When I receive data from Microsoft Active Directory it is an "ad_object" and has the type unicode. When I try to convert it to a string I get this error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 26: ordinal not in range(128) This is caused by characters like the german ä, ö or ü.
4
25070
by: meendar | last post by:
Hi, I am having a character pointer which contains ascii values. i just want to convert all these ascii values to respective characters and again store it in another character pointer. Anybody please help in c language. Thanks in Advance.
19
5351
by: est | last post by:
From python manual str( ) Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.
12
4979
by: aatif | last post by:
I want to convert a string of hex characters (2 hex chars = 1 byte), to ASCII. Hex chars include zeros (0x00) as well, which I want to include in ASCII string. hex string: 5000005355.... ASCII: P<null><null>SU... I can do it and the string length also includes nulls but when I concatenate other string, it doesn't show as its part. string HexValue = "500000535500";
0
9602
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7661
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5688
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.