C# change console encoding error (bad descriptor) - c#

Today i run Visual Studio and open my project, that i not opened about 5 months.
And running test (it was be OK) invoke IOException with additional information: "Bad descriptor".
It was in this line:
var defaultConsoleEncoding = Console.InputEncoding;
Console.InputEncoding = TryGetEncoding("UTF-8"); // <--- There is error
...
public static Encoding TryGetEncoding(string encoding)
{
try
{
return Encoding.GetEncoding(encoding);
}
catch (ArgumentException)
{
Logger.WarnAndPrint($"Can't using {encoding} encoding. Fallback to utf-8");
return Encoding.UTF8;
}
}
All my tests were OK, but now all fails with that error. I never chage code in project. And i try many encodings - nothing work.
What's the problem?
P.S. This is stack trace
System.IO.IOException was unhandled by user code
HResult=-2147024890
Message=Неверный дескриптор.
Source=mscorlib
StackTrace:
в System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
в System.Console.set_InputEncoding(Encoding value)
в PasswordListGenerator.Substitutions.Substitution.Process() в C:\GITHUB\passwordlistgenerator\PasswordListGenerator\PasswordListGenerator\Substitutions\Substitution.cs:строка 89
в PasswordListGeneratorTest.SubstitutionTests.SkipManySymbols_ShouldReturnSubstitutions() в C:\GITHUB\passwordlistgenerator\PasswordListGenerator\PasswordListGeneratorTest\SubstitutionTests.cs:строка 588
InnerException:

Related

ConfigurationManager.OpenMappedExeConfiguration "because it is being used by another process"

I'd like to re-read the MySolution.main.config (my app.config) thanks FileSystemWatcher when users modify it. I built a wrapper called FileWatcher.
Catching OnChanged event with this piece of code
var map = new ExeConfigurationFileMap { ExeConfigFilename = _appConfigFilePath };
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
raises this exception
System.Configuration.ConfigurationErrorsException HResult=0x80131902
Message=An error occurred loading a configuration file: The process
cannot access the file
'C:\Source\Solutions\MySolution_1.2.3\MySolution\bin\Debug\MySolution.main.config'
because it is being used by another process.
(C:\Source\Solutions\MySolution_1.2.3\MySolution\bin\Debug\MySolution.main.config)
Source=System.Configuration.ConfigurationManager StackTrace: at
System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean
ignoreLocal) in
//src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationSchemaErrors.cs:line
71 at
System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors
schemaErrors) in
//src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs:line
3634 at System.Configuration.Configuration..ctor(String
locationSubPath, Type typeConfigHost, Object[]
hostInitConfigurationParams) in
//src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Configuration.cs:line
75 at
System.Configuration.ClientConfigurationHost.OpenExeConfiguration(ConfigurationFileMap
fileMap, Boolean isMachine, ConfigurationUserLevel userLevel, String
exePath) in
//src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs:line
485 at
System.Configuration.ConfigurationManager.OpenExeConfigurationImpl(ConfigurationFileMap
fileMap, Boolean isMachine, ConfigurationUserLevel userLevel, String
exePath, Boolean preLoad) in
//src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs:line
214 at
System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ExeConfigurationFileMap
fileMap, ConfigurationUserLevel userLevel) in
//src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs:line
192 at
Siav.MySolution.Log.ConfigurationUtil.FileWatcher.OnChanged(Object
sender, FileSystemEventArgs e) in
C:\Source\Solutions\MySolution_1.2.3\Siav.MySolution.Log\ConfigurationUtil\FileWatcher.cs:line
60 at System.IO.FileSystemWatcher.OnChanged(FileSystemEventArgs e)
in f:\dd\NDP\fx\src\services\io\system\io\FileSystemWatcher.cs:line
822 at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32
action, String name) in
f:\dd\NDP\fx\src\services\io\system\io\FileSystemWatcher.cs:line 773
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer) in
f:\dd\NDP\fx\src\services\io\system\io\FileSystemWatcher.cs:line 594
at
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) in
f:\dd\ndp\clr\src\BCL\system\threading\overlapped.cs:line 121
This exception was originally thrown at this call stack:
System.IO.__Error.WinIOError(int, string) in __error.cs
System.IO.FileStream.Init(string, System.IO.FileMode, System.IO.FileAccess, int, bool, System.IO.FileShare, int,
System.IO.FileOptions,
Microsoft.Win32.Win32Native.SECURITY_ATTRIBUTES, string, bool, bool,
bool) in filestream.cs
System.IO.FileStream.FileStream(string, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare) in filestream.cs
System.Configuration.Internal.InternalConfigHost.StaticOpenStreamForRead(string)
in InternalConfigHost.cs
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.OpenStreamForRead(string)
in InternalConfigHost.cs
System.Configuration.ClientConfigurationHost.OpenStreamForRead(string)
in ClientConfigurationHost.cs
System.Configuration.UpdateConfigHost.OpenStreamForRead(string) in UpdateConfigHost.cs
System.Configuration.ImplicitMachineConfigHost.OpenStreamForRead(string)
in ImplicitMachineConfigHost.cs
System.Configuration.BaseConfigurationRecord.InitConfigFromFile() in BaseConfigurationRecord.cs
Inner Exception 1: IOException: The process cannot access the file
'C:\Source\Solutions\MySolution_1.2.3\MySolution\bin\Debug\MySolution.main.config'
because it is being used by another process.
I tried with a simple lock, it doesn't work.
This is the constructor of my wrapper
public FileWatcher(string appConfigFilePath)
{
_appConfigFilePath = appConfigFilePath;
_lastRead = DateTime.MinValue;
var watcher = new FileSystemWatcher(Path.GetDirectoryName(_appConfigFilePath))
{
Filter = Path.GetFileName(_appConfigFilePath),
NotifyFilter = NotifyFilters.LastWrite,
EnableRaisingEvents = true
};
watcher.Changed += OnChanged;
watcher.Error += OnError;
}
Any suggestions?
Thanks
I had to manage some retry to access the file as log4net does. I suggest to you to do the same (log4net source is available on github)

Cudafy.Net System.ComponentModel.Win32Exception: The system cannot find the file specified

I downloaded cudafy here: https://github.com/lepoco/CUDAfy.NET/releases/tag/v.1.0.0.
I use VS 2022, .NET 4.8.
When executing this code, I get System.ComponentModel.Win32Exception.
CudafyModes.Target = eGPUType.Cuda;
CudafyModes.DeviceId = 0;
CudafyTranslator.Language = CudafyModes.Target == eGPUType.OpenCL ? eLanguage.OpenCL : eLanguage.Cuda;
if (CudafyHost.GetDeviceCount(CudafyModes.Target) == 0)
throw new System.ArgumentException("No suitable devices found.", "original");
GPGPU gpu = CudafyHost.GetDevice(CudafyModes.Target, CudafyModes.DeviceId);
CudafyModule km = CudafyTranslator.Cudafy(); //THE EXCEPTION IS HERE
gpu.LoadModule(km);
StackTrace:
in System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
in Cudafy.NvccExe.getClExeDirectory()
in Cudafy.CompilerHelper.Create(ePlatform platform, eArchitecture arch, eCudafyCompileMode mode, String workingDir, Boolean debugInfo)
in Cudafy.Translator.CudafyTranslator.Cudafy()
in Game.Position..ctor() in C:\Users\Lenovo\Desktop\simple\simple\Position.cs:line 464
in Game.Position.StartPos() in C:\Users\Lenovo\Desktop\simple\simple\Position.cs:line 490
in Game.Board..ctor() in C:\Users\Lenovo\Desktop\simple\simple\Board.cs:line 189
in Game.FrmMain..ctor() in C:\Users\Lenovo\Desktop\simple\simple\FrmMain.cs:line 18
in Game.Program.Main() in C:\Users\Lenovo\Desktop\simple\simple\Program.cs:line 19
Exception information:
ErrorCode -2147467259 int
HResult -2147467259 int
HelpLink null string
InnerException null
NativeErrorCode 2 int
Source "System" string
TargetSite {Boolean StartWithCreateProcess(System.Diagnostics.ProcessStartInfo)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
The Path environment variable is declared:
Path C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\bin\Hostx64\x64
Cuda Toolkit 11.6 has been downloaded.
What can I do about it?
I solved the problem by connecting the source code. In particular, the program did not find the path to the utility vswhere.exe. Also the CUDA Toolkit required VS2010.

Access to folder Denied C#

I'm a fairly new C# Programmer, and I've run into an error beyond my ability to fix.
Currently I'm working on coding a discord bot, and upon trying to instantiate and Program object, it returns an "Access is denied error".
The issue is that the error is referring to a folder, not a file and I've tried a bunch of stuff to fix it.
Running Visual Studio as administrator
Ensuring my account has permissions to access the files and folder
Changing the location of the project files
Restarting visual Studio
Recoding the project off a clean sheet
Ensuring the folder and files are not "Read Only"
The error is thrown at this line: => new Program().MainAsync().GetAwaiter().GetResult();
I'm basically out of ideas at this point. The full details of the exception message are as follows:
System.UnauthorizedAccessException
HResult=0x80070005
Message=Access to the path 'C:\Users\XXX\source\repos\discordBot\discordBot\bin\Debug' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at train_bot.Program.d__3.MoveNext() in C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 46
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at train_bot.Program.Main(String[] args) in C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 21
The less detailed version
System.UnauthorizedAccessException: 'Access to the path 'C:\Users\SettingAdmin\source\repos\discordBot\discordBot\bin\Debug' is denied.'
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
namespace train_bot
{
class Program
{
private DiscordSocketClient Client;
private CommandService Commands;
static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
private async Task MainAsync()
{
//configuring client
Client = new DiscordSocketClient(new DiscordSocketConfig
{
LogLevel = LogSeverity.Debug //changes detail in log
});
Commands = new CommandService(new CommandServiceConfig
{
CaseSensitiveCommands = true,
DefaultRunMode = RunMode.Async,
LogLevel = LogSeverity.Debug
});
Client.MessageReceived += Client_MessageReceived;
await Commands.AddModulesAsync(Assembly.GetEntryAssembly());
Client.Ready += Client_Ready;
Client.Log += Client_Log;
string Token = "";
using (var Steam = new FileStream(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace(#"bin\Debug\netcoreapp2.0", #"Token.txt"), FileMode.Open, FileAccess.Read))using (var ReadToken = new StreamReader(Steam))
{
Token = ReadToken.ReadToEnd();
}
await Client.LoginAsync(TokenType.Bot, Token);
await Client.StartAsync();
await Task.Delay(-1);
}
private async Task Client_Log(LogMessage Message)
{
Console.WriteLine($"{DateTime.Now} at {Message.Source}] {Message.Message}");
}
private async Task Client_Ready()
{
await Client.SetGameAsync("Hentai King 2018", "", StreamType.NotStreaming);
}
private async Task Client_MessageReceived(SocketMessage arg)
{
//Configure the commands
}
}
}
The problem may be that you try to open a directory as file. The path you construct is:
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace(#"bin\Debug\netcoreapp2.0", #"Token.txt")
This would only work if Assembly.GetEntryAssembly().Location indeed contains the string #"bin\Debug\netcoreapp2.0".
You probably intended something like
Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), #"Token.txt")
Like the error said, you don't have access to that folder. If you are running it on debug mode make sure you run visual studio as administrator so you get to ignore all that on dev environment. If its deployed, make sure the the account running your program has appropriate rights to the folder.

ComException HRESULT: 0x800A03EC thrown when attempting to add Validation to a Range

When trying to use the Range.Validation.Add() method, I'm consistently getting a very unfriendly error:
************** Exception Text **************
System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
at Microsoft.Office.Interop.Excel.Validation.Add(XlDVType Type, Object AlertStyle, Object Operator, Object Formula1, Object Formula2)
at TravelPlannerTools.Sheet8.OperaCodesDropDown() in C:\Users\Michael Utz\Documents\Visual Studio 2015\Projects\TravelPlannerTools\TravelPlannerTools\Sheet8.cs:line 39
at TravelPlannerTools.Sheet8.Sheet8_Startup(Object sender, EventArgs e) in C:\Users\Michael Utz\Documents\Visual Studio 2015\Projects\TravelPlannerTools\TravelPlannerTools\Sheet8.cs:line 27
at Microsoft.Office.Tools.Excel.WorksheetImpl.OnStartup()
at Microsoft.Office.Tools.Excel.WorksheetImpl.WorksheetExtensionImpl.Microsoft.Office.Tools.EntryPoint.OnStartup()
at Microsoft.Office.Tools.Excel.WorksheetBase.OnStartup()
at TravelPlannerTools.Sheet8.FinishInitialization() in C:\Users\Michael Utz\Documents\Visual Studio 2015\Projects\TravelPlannerTools\TravelPlannerTools\Sheet8.Designer.cs:line 50
at Microsoft.Office.Tools.Excel.WorksheetBase.Microsoft.Office.Tools.EntryPoint.FinishInitialization()
at Microsoft.VisualStudio.Tools.Office.Runtime.DomainCreator.ExecuteCustomization.ExecutePhase(ExecutionPhases executionPhases)
at Microsoft.VisualStudio.Tools.Office.Runtime.DomainCreator.ExecuteCustomization.Microsoft.VisualStudio.Tools.Office.Runtime.Interop.IExecuteCustomization2.ExecuteEntryPoints()
************** Loaded Assemblies **************
I am using the proper version of Excel and trying to perform a very simple task.
var list = new List<string>();
list.Add("Lann");
list.Add("Latl");
list.Add("LBBB");
var flatList = string.Join(",", list.ToArray());
var cell = Globals.Sheet8.Cells.Range["A2"];
cell.Validation.Delete();
cell.Validation.Add(
Excel.XlDVType.xlValidateList,
Excel.XlDVAlertStyle.xlValidAlertStop,
Excel.XlFormatConditionOperator.xlBetween,
flatList,
System.Type.Missing
);
cell.Validation.IgnoreBlank = true;
cell.Validation.InCellDropdown = true;
Any ideas?
The cell I was trying to write to was on a protected sheet. Using the Worksheet.Protect() and Worksheet.Unprotect() methods to toggle protection before and after the operation cleared up the error!

Comparison of two XMLs - "illegal characters in path"

When I try to use Compare function from MS API (XmlDiffPatch), it give me an error "illegal characters in path".
This is my code:
public void CompareXMLStructer(string a, string b)
{
try
{
using (var fs = new FileStream(#"C:\Test\result.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
var diffWriter = XmlWriter.Create(fs);
var xmlDiff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder |
XmlDiffOptions.IgnoreNamespaces |
XmlDiffOptions.IgnorePrefixes);
var identical = xmlDiff.Compare(a, b, false, diffWriter);
MessageBox.Show(identical ? "YES" : "NO");
diffWriter.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Exception:
Exception thrown: 'System.ArgumentException' in mscorlib.dll
System.ArgumentException: Niedozwolone znaki w ścieżce. //<-That means Illegal expresion in path
w System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
w System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
w System.IO.Path.GetFullPathInternal(String path)
w System.Xml.XmlResolver.ResolveUri(Uri baseUri, String relativeUri)
w System.Xml.XmlUrlResolver.ResolveUri(Uri baseUri, String relativeUri)
w System.Xml.XmlTextReaderImpl..ctor(String url, XmlNameTable nt)
w System.Xml.XmlTextReader..ctor(String url)
w Microsoft.XmlDiffPatch.XmlDiff.OpenDocuments(String sourceFile, String changedFile, XmlReader& sourceReader, XmlReader& changedReader)
w Microsoft.XmlDiffPatch.XmlDiff.Compare(String sourceFile, String changedFile, Boolean bFragments, XmlWriter diffgramWriter)
w WindowsFormsApplication1.Comparision.CompareXMLStructer(String a, String b) w C:\Users\zos-srv\documents\visual studio 2015\Projects\Porownywarka\WindowsFormsApplication1\Comparision.cs:wiersz 44
The thread 0x1334 has exited with code 0 (0x0).
Can it be caused by \r, \n etc. in my string or maybe encoding is wrong?
string:
a "<?xml version=\"1.0\" encoding=\"Windows-1250\"?>\r\n<Dokument idDokumentu=\"6183457\" numer=\"32178.2015\" idSprawy=\"6187041\" wersja=\"1\" dataDokumentu=\"2015-09-09T00:00:00\" numerObcy=\"\" rodzajObcy=\"\" idObcy=\"\" vidObcy=\"\" wersjonowanie=\"0\" statusBIP=\"E\" korespSystemWew=\"N\" nrWgRejestru=\"\" system=\"EDOKUMENT\" oznWysylka=\"true\" wysylka=\"false\" odbiorOsobisty=\"false\" kopia=\"false\" kodKreskowy=\"\" dostep=\"1\" format=\"\" typ_dublin_core_metadata=\"8\" rwa=\"0003\" znakDokumentu=\"\" obcy=\"false\" odwzorowanie=\"\" znak_sprawy_alt=\"\" kat_arch=\"A\" idDokumentuPierw=\"0\" numerWSprawie=\"4\" czySaUwagi=\"false\" ntas=\"false\" idSkladuChronologicznego=\"0\" zatwierdzonyUzytk=\"true\">\r\n <Opis>\r\n <![CDATA[Testowy dokument]]>\r\n </Opis>\r\n <Notatka>\r\n <![CDATA[]]>\r\n </Notatka>\r\n <Typ idTypu=\"12938\" nazwa=\"OR Inne\" kategoriaBIP=\"\" sciezkaBIP=\"\" podlegaZatwierdzaniu=\"true\" czyBip=\"false\"/>\r\n <Status idStatusu=\"0\" nazwa=\"\"/>\r\n <Podmiot idPodmiotu=\"6183458\" typPodmiotu=\"G\" idPodmiotuExt=\"5573\" rodzajPodmiotu=\"K\" imie=\"\" nazwisko=\"\" nazwaFirmy=\"Rekord Systemy Informatyczne Sp.z o.o.\" nazwaSkroconaFirmy=\"REKORD\" PESEL=\"\" NIP=\"\" REGON=\"\" idZewnetrzne=\"\" rodzajPodmiotuExt=\"F\" email=\"\">\r\n <Adres kodPocztowy=\"43-300\" miasto=\"Bielsko-Biała\" ulica=\"Kasprowicza\" numerDomu=\"5\" numerLokalu=\"\" kraj=\"Polska\" adresSkrytki=\"\" dzielnica=\"\" skrytkaPocztowa=\"\" adresZagraniczny=\"false\"/>\r\n </Podmiot>\r\n <Folder idFolderu=\"4823\" nazwa=\"MIROSŁAW ZIAJA\"/>\r\n <Utworzenie symbolPracownika=\"216\" nazwisko=\"ZIAJA\" imie=\"MIROSŁAW\" data=\"2015-09-09T11:48:36\"/>\r\n <Dysponenci>\r\n <Dysponent ident=\"6183461\" symbolPrac=\"216\" nazwisko=\"MIROSŁAW ZIAJA\" imie=\"\" wiodacy=\"true\" tylko.do.odczytu=\"false\" obcyId=\"\" obcyLogin=\"\" stanowisko=\"Inspektor (OR-o)\" rodzaj=\"P\"/>\r\n </Dysponenci>\r\n <Zatwierdzenia>\r\n <Zatwierdzenie data=\"2015-09-14T14:24:44\" rodzaj=\"1\" czyBlokuje=\"true\" kierownicze=\"false\">\r\n <Pracownik symbolPracownika=\"216\" nazwisko=\"ZIAJA\" imie=\"MIROSŁAW\" stanowisko=\"\" stanowiskoIdent=\"0\" pracIdent=\"216\" funkcjaIdent=\"0\"/>\r\n </Zatwierdzenie>\r\n </Zatwierdzenia>\r\n</Dokument>\r\n"
As you can read in the stack trace, the first two strings of xmlDiff.Compare(string, string, ...) accept paths, not XML strings.
I don't know where the documentation for this library resides, so I don't know whether there are Stream overloads, for example. If there aren't, just temporarily write the files to disk.

Categories