- Remove From My Forums
-
Question
-
I had 3 XAML windows in my projet. The next, day, I delete one of them via the visual studio interface. However, when I try to compile my projet, it says ‘Could not find the file [my xaml file]’ after I deleted it. I do know how to make the compiler stop
looking for the file
All replies
-
I had 3 XAML windows in my projet. The next, day, I delete one of them via the visual studio interface. However, when I try to compile my projet, it says ‘Could not find the file [my xaml file]’ after I deleted it. I do know how to make the compiler
stop looking for the fileHi Vindi Quartz,
When you delete the file make sure you save the project file. What happens is the CSproj still has a compile reference to the old file path, and can’t find it.
You can refer the following workaround: All files are saved when compilation is invoked.
Incremental build fails after rename of XAML file
Besides, this issue is more related to the visual studio, you can go to the
Visual Studio General Questions forum.Best Regards
Yong Lu
MSDN Community Support
Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
MSDN Support, feel free to contact MSDNFSF@microsoft.com.
82 / 60 / 17 Регистрация: 21.08.2015 Сообщений: 1,046 |
|
1 |
|
Добавил потом удалил окно, получил ошибку01.02.2017, 10:01. Показов 3228. Ответов 0
Добрый день. Добавил в проект «Окно» и «Страницу», потом удалил, теперь вижу такую вот ошибку Ошибка Неизвестная ошибка сборки, «Файл ‘C:PROJECTSC-SharpWPF_PROJECTSCompositionCompositionPage1.xaml’ не найден.» Где у него спрятаны ссылки на эту страницу? Не могу понять как избавится от ошибки. Добавлено через 34 минуты
1 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
01.02.2017, 10:01 |
0 |
При сборке решения своего проекта wpf довольно часто получаю ошибку:
не удалось скопировать файл "objDebug{ProjectName}.exe" - файл не найден.
Я не первый, кто столкнулся с подобной проблемой. Пробовал много различных советов, таких, как смена версии целевой платформы, обновление .net framework, переустановка visual studio и т.д.
Единственной, что мне помогает, это перезапук visual studio (не каждый раз срабатывает).
А самое удивительное для меня, что всегда помогает изменение AssemblyVersion в файле AssemblyInfo.cs, я просто изменяю цифру в версии с 1.0.0.0 (дефолт) на 2.0.0.0 и решение собирается без ошибок, но через некоторое время ошибка появляется снова и тогда приходится изменять версию снова.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Для меня остается секретом суть данной проблемы, подскажите, пожалуйста, как мне окончательно избавиться от этой ошибки.
PS: решение небольшое, состоит из одного одностраничного проекта WPF и библиотеки .dll, написанной мной, но вне данного решения, библиотека работает без проблем.
Из сторонних библиотек использую Microsoft.Toolkit.Wpf.UI.Controls для взаимодействия с картой
UPD: Данная проблема появилась и в других проектах WPF, в том числе и тех, что не используют сторонние библиотеки.
В не WPF проектах (WinForms, DLL-library, Console Application) получить ошибку так и не получилось
UPD2:
Заметил, что при сборке решения, все ошибки дублируются.
Код, вызывающий ошибку
InputErrors inputErrors = new InputErrors(initData); // конструктор не принимает аргумент initData
SaveInitDataHandler += inputErrors.InputErrors_SaveInitDataHandler //пропущено ";"
- .NET Core Version: SDK 3.0.100-preview-009812
- OS version: macOS Mojave v 10.14.1
- Does the bug reproduce also in WPF for .NET Framework 4.8?: No
Problem description: After creating WPF project by running dotnet -new wpf command, dotnet build command fails with file not found errors.
Actual behavior:
A sample error is displayed below. The file exists however it seems that path separator is not correct which may be causing this build failure e.g. for root path and App.xaml.
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1002: File ‘/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFAppApp.xaml’ cannot be found. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1002: File ‘MainWindow.xaml’ cannot be found. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1003: The project file contains a property value that is not valid. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
Build FAILED.
Expected behavior:
Expected dotnet build to succeed.
Minimal repro:
- On a Mac, I have installed lastest sdk from
https://dotnet.microsoft.com/download/dotnet-core/3.0 - Executed dotnet -new wpf -o SampleWPFApp command
- Changed current folder in terminal to SampleWPFApp
- Executed dotnet build however it fails
I don’t think WPF has been/will be ported to MacOS
Does the bug reproduce also in WPF for .NET Framework 4.8 on MacOS?:
Does the bug reproduce also in WPF for .NET Framework 4.8 on MacOS?:
LOL
I don’t think WPF has been/will be ported to MacOS
Correct. WPF is Windows only.
Thanks for the confirmation that WPF projects won’t be supported on macOS.
I don’t think we should block anything on dotnet new
. You could just as easily clone or type in the same project. As such, the right place to verify is in the build. That said, without committing to anything, building wpf from non-Windows (cross compilation) is separate from running an application. The former can be made to work without the latter. Again, I am not committing to anything here, but it might be possible to make dotnet build
work and leave the failure to dotnet run
, which would tell you that there is no WindowsDesktop runtime.
karelz, atverma, Lakritzator, kvalev, hsorbo, tdjastrzebski, istupakov, listm, Sejsel, wgnf, and 3 more reacted with thumbs up emoji
Guessing from the error message, it looks like the first thing hit here is a ‘/’ vs » mixup.
OK, that makes sense. Let’s see if more people hit this problem then and if it is something we should address sooner rather than later to provide more clarity …
Quick inspection, there are some hard-coded » in the build task source. There is also a mismatch of Microsoft.WinFX.targets in import vs Microsoft.WinFx.targets, which will cause this to fail even earlier on Linux. These are easy enough to fix, the question is whether something bigger lurks behind them.
@nguerrera I just encountered both issues that you mentioned, but I couldn’t find the Microsoft.NET.Sdk.WindowsDesktop.targets
sources anywhere. Am I right to assume that they have not been open sourced yet?
OK, that makes sense. Let’s see if more people hit this problem then and if it is something we should address sooner rather than later to provide more clarity …
FWIW I just hit this issue as well. Running
.NET Core SDK (reflecting any global.json):
Version: 3.0.100-preview-010184
Commit: c57bde4593
I’ve also understood it that WPF is not and will not be supported on mac OS but after being encouraged by this post I gave it a try, which lead led to the issue at runtime.
In fact it seems possible to build WPF/WinForms projects from non Windows (Tested with bionic/amd64, we don’t use mac) with a quite simple patch (here on .NET Core 3.0 Preview5). There was two problems to address
- Microsoft.WinFx.targets casing required to be harmonized (for case sensitive file systems)
- PresentationBuildTasks assembly source code used hard coded const string » as directory separator in several locations
As a result, we seem to be able to build WPF/WinForms assemblies from Linux (cross compilation). I see the two markup compilation phases happening for WPF and diffing assemblies between plain Windows non patched build and Linux patched build gives the exact same outputs. Cross compiling is quite useful as we now can CI/CD using a lightweight Ubuntu-x64 docker image (instead of a quite big Windows VM). It should also probably work from other Unix flavours (Mac, etc …).
If someone is interested I will create a PR
Patch (Could do PR)
daviddenis-stx@a9b28ed
Docker images (Testing, not for PR)
daviddenis-stx@d122d93
@daviddenis-stx did you test this with custom Controls and MarkupExtensions? I don’t know the technical details of the markup compilation phase but I’d expect it to require loading the assembly and possibly even running some code? If so, then cross compiling could become pretty fragile as soon as 3rd party controls using Windows features are involved. When going this route it should be made sure that the error messages are appropriate when loading or execution of assemblies fails during markup compilation.
I tried to compile code using controls from Xceed extended WPF toolkit (restored as net 461). The build goes through and diffing the assemblies give something identical (the baml resources are not binary identical but decompiling them with ILSpy gives binary identical xaml text). Ideally we would need a great deal of unit testing. I’m curious of anybody willing to try to compile something of their own making to see how all that goes
At least this patch would correct self evident mistakes that prevent the build to even occur. I agree that it requires a lot of testing. We will do that on all our UIs and get back with more materials (proper runtime testing on Windows) but it’s probably not covering all the possibles. I guess it mostly boils down to underlying dependencies (are they net standard? do they use pinvoke? properly made nugets ?) if assembly loading happens it’s not clear why it would work on netcore windows and not linux?
Let’ s compile more WPF code with the proposed docker images, then diff assemblies, then execute. We should know rapidly if something bites.
if assembly loading happens it’s not clear why it would work on netcore windows and not linux?
C++/CLI doesn’t load on Linux/Mac, so if you’re using any type from such an assembly (possibly indirectly) it could trigger a failed assembly load, possibly cascading back to types failing to load in other assemblies.
I don’t expect it to be the common case, I just want to make sure this edge case is considered and has a reasonable diagnostic.
Makes sense. We had to just exclude C++/CLI assemblies from our codebase when migrating to netcore (I talk non UI assemblies). We may want to find a thirdparty with such a construction to test but it’s probable that those are going to dissappear eventually.
For the record, we stumbled upon some WinForms only issues when building with dotnet build
(even on Windows). The build goes through but exceptions are thrown when executing.
As of .NET Core 3.0 preview5, you still have to build WinForms assemblies with msbuild.exe
because .resx files are not handled correctly if you build with dotnet build
.
For example the code below will execute without problem if built using VS2019 and fail with exception if built using dotnet build
(System.Windows.Forms.ImageListStreamer)resources.GetObject("imageList.ImageStream");
dotnet/msbuild#2221
WinForms will have more problems, for example licensed controls (licx) need to execute at build time to generate the license. Also natively wrapped controls are far more common in WinForms than in WPF. If they are licensed those will definitely not work on non-Windows builds. WinForms already has issues dotnet/winforms#947 and dotnet/winforms#971 for enabling Linux builds though, and I added corresponding remarks there.
If someone is interested I will create a PR
Patch (Could do PR)
systemathics@a9b28ed
Hi!
I tried to use your PR(fork) on my Ubuntu 18.04(x64) + net core 5.0.0-preview.1.20120.5, so I updated configuration file global.json to such state:
{
«tools»: {
«dotnet»: «5.0.100-alpha1-015536»,
«vs»: {
«version»: «16.1»
}
},
«sdk»: {
«version»: «5.0.100-alpha1-015536»
},
«msbuild-sdks»: {
«Microsoft.DotNet.Arcade.Sdk»: «5.0.0-beta.20171.1»,
«Microsoft.DotNet.Helix.Sdk»: «5.0.0-beta.20171.1»,
«FIX-85B6-MERGE-9C38-CONFLICT»: «1.0.0»,
«Microsoft.NET.Sdk.IL»: «5.0.0-alpha1.19513.3»
},
«native-tools»: {
«strawberry-perl»: «5.28.1.1-1»
}
}
Now after executing build.sh I got the error message (I report it here because don’t now whether is possibility to report about issue in fork):
maestro@mmeniac:~/..msv_links/C#/libs_and_so_on/Enable_WinForms_WPF_Unix/wpf$ sudo ./build.sh
/home/maestro/Documents/code/C#/libs_and_so_on/Enable_WinForms_WPF_Unix/wpf/eng/common/init-tools-native.sh: line 120: /home/maestro/Documents/code/C#/libs_and_so_on/Enable_WinForms_WPF_Unix/wpf/eng/common/native/install-strawberry-perl.sh: No such file or directory
Execution Failed
Is there a workaround to somehow build this fork?
msftbot
bot
locked as resolved and limited conversation to collaborators
Apr 18, 2022
- .NET Core Version: SDK 3.0.100-preview-009812
- OS version: macOS Mojave v 10.14.1
- Does the bug reproduce also in WPF for .NET Framework 4.8?: No
Problem description: After creating WPF project by running dotnet -new wpf command, dotnet build command fails with file not found errors.
Actual behavior:
A sample error is displayed below. The file exists however it seems that path separator is not correct which may be causing this build failure e.g. for root path and App.xaml.
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1002: File ‘/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFAppApp.xaml’ cannot be found. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1002: File ‘MainWindow.xaml’ cannot be found. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
/usr/local/share/dotnet/sdk/3.0.100-preview-009812/Sdks/Microsoft.NET.Sdk.WindowsDesktop/targets/Microsoft.WinFX.targets(243,9): error BG1003: The project file contains a property value that is not valid. [/Users/atverma/Documents/GitHub/DotNetCoreWPFApp/MyWPFApp/MyWPFApp.csproj]
Build FAILED.
Expected behavior:
Expected dotnet build to succeed.
Minimal repro:
- On a Mac, I have installed lastest sdk from
https://dotnet.microsoft.com/download/dotnet-core/3.0 - Executed dotnet -new wpf -o SampleWPFApp command
- Changed current folder in terminal to SampleWPFApp
- Executed dotnet build however it fails
I don’t think WPF has been/will be ported to MacOS
Does the bug reproduce also in WPF for .NET Framework 4.8 on MacOS?:
Does the bug reproduce also in WPF for .NET Framework 4.8 on MacOS?:
LOL
I don’t think WPF has been/will be ported to MacOS
Correct. WPF is Windows only.
Thanks for the confirmation that WPF projects won’t be supported on macOS.
I don’t think we should block anything on dotnet new
. You could just as easily clone or type in the same project. As such, the right place to verify is in the build. That said, without committing to anything, building wpf from non-Windows (cross compilation) is separate from running an application. The former can be made to work without the latter. Again, I am not committing to anything here, but it might be possible to make dotnet build
work and leave the failure to dotnet run
, which would tell you that there is no WindowsDesktop runtime.
karelz, atverma, Lakritzator, kvalev, hsorbo, tdjastrzebski, istupakov, listm, Sejsel, wgnf, and 3 more reacted with thumbs up emoji
Guessing from the error message, it looks like the first thing hit here is a ‘/’ vs » mixup.
OK, that makes sense. Let’s see if more people hit this problem then and if it is something we should address sooner rather than later to provide more clarity …
Quick inspection, there are some hard-coded » in the build task source. There is also a mismatch of Microsoft.WinFX.targets in import vs Microsoft.WinFx.targets, which will cause this to fail even earlier on Linux. These are easy enough to fix, the question is whether something bigger lurks behind them.
@nguerrera I just encountered both issues that you mentioned, but I couldn’t find the Microsoft.NET.Sdk.WindowsDesktop.targets
sources anywhere. Am I right to assume that they have not been open sourced yet?
OK, that makes sense. Let’s see if more people hit this problem then and if it is something we should address sooner rather than later to provide more clarity …
FWIW I just hit this issue as well. Running
.NET Core SDK (reflecting any global.json):
Version: 3.0.100-preview-010184
Commit: c57bde4593
I’ve also understood it that WPF is not and will not be supported on mac OS but after being encouraged by this post I gave it a try, which lead led to the issue at runtime.
In fact it seems possible to build WPF/WinForms projects from non Windows (Tested with bionic/amd64, we don’t use mac) with a quite simple patch (here on .NET Core 3.0 Preview5). There was two problems to address
- Microsoft.WinFx.targets casing required to be harmonized (for case sensitive file systems)
- PresentationBuildTasks assembly source code used hard coded const string » as directory separator in several locations
As a result, we seem to be able to build WPF/WinForms assemblies from Linux (cross compilation). I see the two markup compilation phases happening for WPF and diffing assemblies between plain Windows non patched build and Linux patched build gives the exact same outputs. Cross compiling is quite useful as we now can CI/CD using a lightweight Ubuntu-x64 docker image (instead of a quite big Windows VM). It should also probably work from other Unix flavours (Mac, etc …).
If someone is interested I will create a PR
Patch (Could do PR)
daviddenis-stx@a9b28ed
Docker images (Testing, not for PR)
daviddenis-stx@d122d93
@daviddenis-stx did you test this with custom Controls and MarkupExtensions? I don’t know the technical details of the markup compilation phase but I’d expect it to require loading the assembly and possibly even running some code? If so, then cross compiling could become pretty fragile as soon as 3rd party controls using Windows features are involved. When going this route it should be made sure that the error messages are appropriate when loading or execution of assemblies fails during markup compilation.
I tried to compile code using controls from Xceed extended WPF toolkit (restored as net 461). The build goes through and diffing the assemblies give something identical (the baml resources are not binary identical but decompiling them with ILSpy gives binary identical xaml text). Ideally we would need a great deal of unit testing. I’m curious of anybody willing to try to compile something of their own making to see how all that goes
At least this patch would correct self evident mistakes that prevent the build to even occur. I agree that it requires a lot of testing. We will do that on all our UIs and get back with more materials (proper runtime testing on Windows) but it’s probably not covering all the possibles. I guess it mostly boils down to underlying dependencies (are they net standard? do they use pinvoke? properly made nugets ?) if assembly loading happens it’s not clear why it would work on netcore windows and not linux?
Let’ s compile more WPF code with the proposed docker images, then diff assemblies, then execute. We should know rapidly if something bites.
if assembly loading happens it’s not clear why it would work on netcore windows and not linux?
C++/CLI doesn’t load on Linux/Mac, so if you’re using any type from such an assembly (possibly indirectly) it could trigger a failed assembly load, possibly cascading back to types failing to load in other assemblies.
I don’t expect it to be the common case, I just want to make sure this edge case is considered and has a reasonable diagnostic.
Makes sense. We had to just exclude C++/CLI assemblies from our codebase when migrating to netcore (I talk non UI assemblies). We may want to find a thirdparty with such a construction to test but it’s probable that those are going to dissappear eventually.
For the record, we stumbled upon some WinForms only issues when building with dotnet build
(even on Windows). The build goes through but exceptions are thrown when executing.
As of .NET Core 3.0 preview5, you still have to build WinForms assemblies with msbuild.exe
because .resx files are not handled correctly if you build with dotnet build
.
For example the code below will execute without problem if built using VS2019 and fail with exception if built using dotnet build
(System.Windows.Forms.ImageListStreamer)resources.GetObject("imageList.ImageStream");
dotnet/msbuild#2221
WinForms will have more problems, for example licensed controls (licx) need to execute at build time to generate the license. Also natively wrapped controls are far more common in WinForms than in WPF. If they are licensed those will definitely not work on non-Windows builds. WinForms already has issues dotnet/winforms#947 and dotnet/winforms#971 for enabling Linux builds though, and I added corresponding remarks there.
If someone is interested I will create a PR
Patch (Could do PR)
systemathics@a9b28ed
Hi!
I tried to use your PR(fork) on my Ubuntu 18.04(x64) + net core 5.0.0-preview.1.20120.5, so I updated configuration file global.json to such state:
{
«tools»: {
«dotnet»: «5.0.100-alpha1-015536»,
«vs»: {
«version»: «16.1»
}
},
«sdk»: {
«version»: «5.0.100-alpha1-015536»
},
«msbuild-sdks»: {
«Microsoft.DotNet.Arcade.Sdk»: «5.0.0-beta.20171.1»,
«Microsoft.DotNet.Helix.Sdk»: «5.0.0-beta.20171.1»,
«FIX-85B6-MERGE-9C38-CONFLICT»: «1.0.0»,
«Microsoft.NET.Sdk.IL»: «5.0.0-alpha1.19513.3»
},
«native-tools»: {
«strawberry-perl»: «5.28.1.1-1»
}
}
Now after executing build.sh I got the error message (I report it here because don’t now whether is possibility to report about issue in fork):
maestro@mmeniac:~/..msv_links/C#/libs_and_so_on/Enable_WinForms_WPF_Unix/wpf$ sudo ./build.sh
/home/maestro/Documents/code/C#/libs_and_so_on/Enable_WinForms_WPF_Unix/wpf/eng/common/init-tools-native.sh: line 120: /home/maestro/Documents/code/C#/libs_and_so_on/Enable_WinForms_WPF_Unix/wpf/eng/common/native/install-strawberry-perl.sh: No such file or directory
Execution Failed
Is there a workaround to somehow build this fork?
msftbot
bot
locked as resolved and limited conversation to collaborators
Apr 18, 2022
I installed the Feb 2010 WPF Toolkit as I’m interested in evaluating the AutoCompleteBox control and I’m having extremely limited success. I can get the control to work, but as soon as I try and set any of it’s properties in XAML, I get the following:
Unknown build error, ‘Cannot resolve dependency to assembly ‘WPFToolkit, Version=3.5.40128.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.
I’ve been testing this on a blank WPF window in a new solution. I’m guessing I’m just missing a reference or something… Here’s the XAML (I’ve added nothing to the .xaml.cs):
<Window x:Class="WpfToolkitApplication.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
Title="Window1" Height="300" Width="300">
<Grid>
<toolkit:AutoCompleteBox Height="25"/>
</Grid>
</Window>
The only reference I’ve added is System.Windows.Controls.Input.Toolkit. Any ideas?
I installed the Feb 2010 WPF Toolkit as I’m interested in evaluating the AutoCompleteBox control and I’m having extremely limited success. I can get the control to work, but as soon as I try and set any of it’s properties in XAML, I get the following:
Unknown build error, ‘Cannot resolve dependency to assembly ‘WPFToolkit, Version=3.5.40128.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.
I’ve been testing this on a blank WPF window in a new solution. I’m guessing I’m just missing a reference or something… Here’s the XAML (I’ve added nothing to the .xaml.cs):
<Window x:Class="WpfToolkitApplication.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
Title="Window1" Height="300" Width="300">
<Grid>
<toolkit:AutoCompleteBox Height="25"/>
</Grid>
</Window>
The only reference I’ve added is System.Windows.Controls.Input.Toolkit. Any ideas?
- Remove From My Forums
Проблема со ссылкой на ресурсы сборки в коде (WPF — VB)
-
Вопрос
-
Есть ряд картинок определенных как ресурсы сборки. При установке свойств source с относительным URI в XAML все работает прекрасно, а вот из кода возникает ошибка «Не найдена часть пути…»
Пример: в XAML — <Window
x:Class=«MainWindow«
… Icon=«/Pict/11.png«>все работает шикарно, а вот в коде —
Dim NotifyInfo As New System.Windows.Forms.NotifyIcon NotifyInfo.Icon = New System.Drawing.Icon(New BitmapImage(New Uri("/Pict/11.png", UriKind.Relative)).StreamSource)
генерит ошибку: Не удалось найти часть пути…. «C:Pict11.png»
Откровенно говоря не знаю что делать и как поступить…
Ответы
-
Действительно, не работает. У меня Background получилось вставить из кода вот так:
Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/Bg.png", UriKind.Absolute)));
- Помечено в качестве ответа
31 марта 2011 г. 16:24
- Помечено в качестве ответа
После установки следующих пакетов NuGet:
- cef.redist.x64
- CefSharp.Common
- CefSharp.Wpf
Следуя следующему видеоруководству: Как создать веб-браузер Cefsharp в WPF C#, добавив файл манифеста приложения и раскомментировав ключ Windows 10.
Затем, ссылаясь на компонент CefSharp
в заголовке окна Xaml: xmlns:cef="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
.
Следуя этим шагам, тег <cef:ChromiumWebBrowser Address="https://google.ca" Height="400" Width="400"/>
должен создать элемент браузера. Вместо этого появляется следующая ошибка, сигнализирующая о том, что строка Xaml:
Неизвестная ошибка сборки, «Не удалось найти сборку CefSharp, Version=107.1.90.0 …’ Либо загрузите эту сборку явно, используя такой метод, как LoadFromAssemblyPath(), или использовать MetadataAssemblyResolver, который возвращает допустимую сборку.
Visual Studio предлагает добавить ссылку на библиотеку CefSharp
, но щелчок по этому предложению всегда терпит неудачу по любой причине.
обращаясь к документации, можно найти минимальный работающий пример. Тем не менее, пример быстрого запуска даже не работал у меня (ошибки сборки и тому подобное).
Прочитав ответы на StackOverflow, может показаться, что требуется правильная установка распространяемого Visual C++, и что отсутствие этой установки может вызвать проблемы со ссылками. Это не решило проблему для меня.
Я также пробовал изменять значения сборки, конфигурации сборки, раскомментировать определенные строки в файле конфигурации, а также обращаться к документации и другим вопросам на StackOverflow. Ни один из них не упомянул наличие точной ошибки.
2 ответа
Проблема связана с обращением к правильным dll. По какой-то причине они не получают ссылку на проект при выполнении установки пакета NuGet.
Пакеты NuGet устанавливаются в общую локальную папку в C:Usersusername.nuget
. Поэтому добавление ссылок на пакеты NuGet вручную у меня сработало.
Добавить > Ссылка на проект… > Обзор… и добавить следующие библиотеки DLL:
- ….nugetpackagescefsharp.wpf107.1.90libnet462CefSharp.Wpf.dll
- ….nugetpackagescefsharp.common107.1.90libnet452CefSharp.Core.dll
- ….nugetpackagescefsharp.common107.1.90libnet452CefSharp.dll
(Папки могут быть пронумерованы по-разному, но это ссылки на CefSharp.Wpf.dll, CefSharp.Core.dll, CefSharp.dll. .)
-1
Denis G. Labrecque
22 Ноя 2022 в 21:08
Согласно вашим тегам, вы используете .Net 6.0, для которого вам нужно использовать пакет CefSharp.Wpf.netcore. Пакет CefSharp.Wpf предназначен для .Net 4.x.
Для .Net 6.0 вам необходимо следовать инструкциям на странице https://github.com/cefsharp/CefSharp/wiki/Quick-Start-For-MS-.Net-5.0-or-больше
Вручную ссылаться на библиотеки DLL не рекомендуется и не требуется.
0
amaitland
22 Ноя 2022 в 22:18
При сборке решения своего проекта wpf довольно часто получаю ошибку:
не удалось скопировать файл "objDebug{ProjectName}.exe" - файл не найден.
Я не первый, кто столкнулся с подобной проблемой. Пробовал много различных советов, таких, как смена версии целевой платформы, обновление .net framework, переустановка visual studio и т.д.
Единственной, что мне помогает, это перезапук visual studio (не каждый раз срабатывает).
А самое удивительное для меня, что всегда помогает изменение AssemblyVersion в файле AssemblyInfo.cs, я просто изменяю цифру в версии с 1.0.0.0 (дефолт) на 2.0.0.0 и решение собирается без ошибок, но через некоторое время ошибка появляется снова и тогда приходится изменять версию снова.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Для меня остается секретом суть данной проблемы, подскажите, пожалуйста, как мне окончательно избавиться от этой ошибки.
PS: решение небольшое, состоит из одного одностраничного проекта WPF и библиотеки .dll, написанной мной, но вне данного решения, библиотека работает без проблем.
Из сторонних библиотек использую Microsoft.Toolkit.Wpf.UI.Controls для взаимодействия с картой
UPD: Данная проблема появилась и в других проектах WPF, в том числе и тех, что не используют сторонние библиотеки.
В не WPF проектах (WinForms, DLL-library, Console Application) получить ошибку так и не получилось
UPD2:
Заметил, что при сборке решения, все ошибки дублируются.
Код, вызывающий ошибку
InputErrors inputErrors = new InputErrors(initData); // конструктор не принимает аргумент initData
SaveInitDataHandler += inputErrors.InputErrors_SaveInitDataHandler //пропущено ";"
- Remove From My Forums
Не удалось загрузить файл или сборку
-
Вопрос
-
При попытке создания проекта приложения WPF, VS2015 (все компоненты обновлены) сообщает:
System.IO.FileLoadException
Не удалось загрузить файл или сборку «Microsoft.Windows.Design.Interaction, Version=4.3.0.0, PublicKeyToken=b03f5f7f11d50a3a» либо одну из их зависимостей. Найденное определение манифеста сборки не соответствует ссылке на сборку. (Исключение
из HRESULT: 0x80131040)
в System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection,
Boolean suppressSecurityChecks)
в System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection,
Boolean suppressSecurityChecks)
в System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection,
Boolean suppressSecurityChecks)
в System.Reflection.Assembly.Load(AssemblyName assemblyRef)
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.AppDomainFactory.AddBindingRedirectForAssembly(String assemblyName, String publicKeyToken, String oldVersion, String newVersion)
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.AppDomainFactory.ConfigureMandatoryAssemblies()
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.AppDomainFactory.ConfigureAppDomain()
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.AppDomainFactory.CreateAppDomainInfo()
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.Initialize()
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedObjectFactory.Initialize()
в Microsoft.VisualStudio.DesignTools.DesignerHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
в Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry, IServiceProvider serviceOverrides)
в Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func`2 func, CancellationToken cancelToken)
в Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.<>c__DisplayClass10_0`1.<StartTask>b__0()
в System.Threading.Tasks.Task`1.InnerInvoke()
в System.Threading.Tasks.Task.Execute()Как избавится от этой проблемы VS2015 переустановил…???
-
Изменено
14 июля 2016 г. 19:24
-
Изменено
Ответы
-
Если у вас версия студии Update 1, то удалите ее и установите RTM VS 2015 версию.
https://www.microsoft.com/en-us/download/details.aspx?id=48146
-
Помечено в качестве ответа
Maksim MarinovMicrosoft contingent staff, Moderator
3 августа 2016 г. 10:25
-
Помечено в качестве ответа