Make Visual Studio minify css and js on publish\compile - visual-studio-2013

I have a project that works that works as a subapplication on a site (actually multiple sites). Among other things, I have several static css and js files in this project. I need to keep those as separate js and css files, but to keep google happy, I'd like to minify those. Those files are likely to be modified in the future, so I'd like to avoid manually minifying them every time they are changed.
Is there some option that would allow me to minify those files on compile or publish (other than writing build events to minify those files using external tools).

The following pertains to VS2015, which has much better support for this scenario.
VS2015 introduces support for task runners like gulp or grunt. You could use one of those, and have a task triggered on project open (i.e. always runs while you're working on the project) which will itself monitor for file changes and run the minimizer (i.e. do it on save).
An intro to gulp in VS2015 is available here.
A simpler alternative on VS2015 is to use the Web Compiler Extension, which basically does the above automagically with less work on your side to set it up.

All solutions I found required using different filenames for the minimized versions, and a lot of extra work to switch between using the normal/minified versions.
Instead, I wanted the compressed JavaScript files to have the original names so I didn't have to change the references in my HTML markup. I could use the normal Javascript files in my development environment, then minimized versions would be automatically deployed when publishing.
I found a simple solution that does just that.
First, install Microsoft Ajax Minifier.
Then, in your Visual Studio project file, just before the closing </Project> tag add the following :
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Microsoft Ajax Minifier\ajaxmin.tasks" />
<Target Name="AfterBuild" Condition="'$(ConfigurationName)'=='Release'">
<ItemGroup>
<JS Include="**\*.js" Exclude="**\*.min.js;obj\**\*.*" />
<CSS Include="**\*.css" Exclude="**\*.min.css;obj\**\*.*" />
</ItemGroup>
<AjaxMin
JsSourceFiles="#(JS)" JsSourceExtensionPattern="\.js$" JsTargetExtension=".jsMIN"
CssSourceFiles="#(CSS)" CssSourceExtensionPattern="\.css$" CssTargetExtension=".cssMIN" />
</Target>
<PropertyGroup>
<CopyAllFilesToSingleFolderForPackageDependsOn>
CustomCollectFiles;
$(CopyAllFilesToSingleFolderForPackageDependsOn);
</CopyAllFilesToSingleFolderForPackageDependsOn>
</PropertyGroup>
<Target Name="CustomCollectFiles">
<ItemGroup>
<MinJS Include="**\*.jsMIN" />
<FilesForPackagingFromProject Include="%(MinJS.Identity)">
<DestinationRelativePath>%(RecursiveDir)%(Filename).js</DestinationRelativePath>
</FilesForPackagingFromProject>
<MinCSS Include="**\*.cssMIN" />
<FilesForPackagingFromProject Include="%(MinCSS.Identity)">
<DestinationRelativePath>%(RecursiveDir)%(Filename).css</DestinationRelativePath>
</FilesForPackagingFromProject>
</ItemGroup>
</Target>
What does the above code do? When you publish in Visual Studio, this code will find every .js and .css file in your source, and create a minified copy using the extension .jsMIN and .cssMIN. It will ignore files that are already minified. Then it will copy these minified files to the deployment folder, using the original file names.
VoilĂ ! You just published minified JS/CSS files, while your original files stay intact on your development environment.
Optional:
Want Ajax Minifier to be packaged with your project? From the Ajax Minifier install folder, you can move AjaxMin.dll and AjaxMinTask.dll directly into your source directory. I put them in my App_Data folder. Once they're somewhere in your source, in Visual Studio right-click them, select Include in Project, and also change their Build Action property to None.
Then in the code I included above, change
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Microsoft Ajax Minifier\ajaxmin.tasks" />
to
<UsingTask TaskName="AjaxMin" AssemblyFile="$(MSBuildProjectDirectory)\App_Data\AjaxMinTask.dll" />
Done.
A troubleshooting tip:
My main code above executes AfterBuild and only when the configuration is Release. That's so it will only run during a publish. If your configuration is named something else, or you want it to run in other circumstances, modify the code as needed.

A nice tool can be downloaded from Visual studio Marketplace.
Bundler & Minifier

Related

visual studio publishing typescript files

It would appear that Visual Studio does not publish .ts files by default but does publish the .map files when using Web Deploy. I found an article which says I should add the following to the .csproj file:
<Target Name="AddTsToContent" AfterTargets="CompileTypeScript" Condition="'$(BuildingProject)' != 'false'">
<ItemGroup>
<Content Include="#(TypeScriptCompile)" Condition="'$(Configuration)'=='Debug'"/>
</ItemGroup>
</Target>
This did in fact seem to work as immediately after adding this the .ts files did in fact publish. Unfortunately I had to immediately remove the setting because after adding this none of typescript project includes worked anymore and the project wouldn't compile because all of a sudden all the path for references were wrong.
/// <reference path="../../sharedlibv2/sharedlibv2/ts/fb.core.ts" />
needed to be
/// <reference path="../../../../sharedlibv2/sharedlibv2/ts/fb.core.ts" />
in order to reference correctly. This path is completely invalid as it goes backward beyond the root of my hard drive, so clearly something is messed up. There are many hundreds of shared project files affected here and the reference this setting seems to require is not going to fly with others using these projects. I am guessing but haven't proven it that there will be other problems show up anyway.
I am using Visual Studio 15.5.7. Is there any other method of getting Visual Studio to publish .ts files via Web Deploy ?

Sync files/directory automatically to Visual Studio project

I'm trying to automatically add an entire folder structure to a VS C++ makefile project. This isn't to make the project build (it'll always build from the scons file), I mostly want to use VS to edit the code/find in projects/intellisense etc.
I've tried the solutions suggested here : Is there a way to automatically include content files into asp.net project file? My project currently includes the tags
<ItemGroup>
<Content Include="$([System.IO.Directory]::GetFiles('$(ProjectDir)..\', '*.cpp', SearchOption.AllDirectories))" />
<Content Include="R:\src\FabricEngine\FabricUI\**\*.*" />
</ItemGroup>
But I haven't had any success - none of the suggestions give me the list of files in Visual Studio. Is this an MSBuild feature that isn't supported by VS perhaps? Or is it limited to managed products? Any suggestions on how to get this working?
Got similar problem and found that used following worked for me:
<None Include="$([System.IO.Directory]::GetFiles('$(MSBuildProjectDirectory)', '*.cpp', SearchOption.AllDirectories))" />
But issue with this is it just takes really long time and crashes if you have lot of files

Does Visual Studio support adding MSBuild tasks to projects?

I'm trying to add some simple MSBuild tasks to a Visual Studio project (VS 2012 Express) - specifically, to create a subdirectory then copy some files to a subdirectory of the output directory ready for packaging.
I see that VS supports custom build steps, which are command-line invocations. However, since VS is based on MSBuild it should be possible to add these directly as MSBuild tasks like the Copy Task in the AfterBuild pre-defined target.
What I can't find is any way to actually add such tasks within the framework of Visual Studio. The documentation only talks about it from an MSBuild perspective, not how it works within Visual Studio's UI. It also doesn't seem to discuss the properties that refer to build output etc there; presumably they're just those used by msbuild its self.
Is there support for MSBuild task management in Visual Studio's UI and it's just crippled out of my Express edition? Or do I have to go hack the project file XML to add MSBuild tasks? Is that supported and the way it's supposed to be done?
I'm used to working with Eclipse and Ant or Maven, where all this is supported within the IDE, though of course you can hack the XML directly. Finding no UI at all for MSBuild task management in Visual Studio is quite confusing. Am I missing the obvious or crippled by using the freebie edition?
For C++ projects, you can use the property
<CppCleanDependsOn>DeleteOutputs;$(CppCleanDependsOn)</CppCleanDependsOn>
instead of defining the BeforeClean target like you did.
From what I read, CallTarget is to be avoided. In your example, you should use DependsOnTargets to do that, as you see in many dummy targets in the MS supplied files. The analogous mechanism of a function where a target just "calls" other targets is done with DependsOnTargets. The flow is not really the same as procedural programming.
Intellisense: I never use it. Is that true for conditional AdditionalIncludeDirectories in the props file only? Go ahead and edit the entry in the proj file where the IDE put it, if you edit the property in the IDE with just one configuration chosen.
(After a bunch more reading I found out how this works):
Visual Studio doesn't seem to expose advanced MSBuild project editing, even though modern vcxproj files are just MSBuild project files with a bunch of extra labeled properties and other entries for Visual Studio IDE specifics. So you have to hack the project XML.
To make it cleaner, only add one line to your actual vcxproj file - an include of a .targets file that contains the rest of your build customisations. e.g, just before the end of the project file, insert:
<Import Project="pg_sysdatetime.targets" />
</Build>
Now create your .targets file with the same structure as any other MSBuild project. Here's mine from the project I've been working on:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- MSBuild extension targets for Visual Studio build -->
<PropertyGroup>
<DistDir>pg_sysdatetime_pg$(PGMAJORVERSION)-$(Configuration)-$(Platform)</DistDir>
</PropertyGroup>
<ItemGroup>
<DocFiles Include="README.md;LICENSE"/>
<ExtensionSourceFiles Include="pg_sysdatetime--1.0.sql;pg_sysdatetime.control"/>
<ExtensionDll Include="$(TargetDir)\pg_sysdatetime.dll"/>
</ItemGroup>
<Target Name="CopyOutputs">
<Message Text="Copying build product to $(DistDir)" Importance="high" />
<Copy
SourceFiles="#(DocFiles)"
DestinationFolder="$(DistDir)"
/>
<Copy
SourceFiles="#(ExtensionDll)"
DestinationFolder="$(DistDir)\lib"
/>
<Copy
SourceFiles="#(ExtensionSourceFiles)"
DestinationFolder="$(DistDir)\share\extension"
/>
</Target>
<Target Name="DeleteOutputs">
<Message Text="Deleting $(DistDir)" Importance="normal" />
<Delete Files="$(DistDir)"/>
</Target>
<!-- Attach to Visual Studio build hooks -->
<Target Name="BeforeClean">
<CallTarget Targets="DeleteOutputs"/>
</Target>
<Target Name="AfterBuild">
<CallTarget Targets="CopyOutputs"/>
</Target>
</Project>
This can contain whatver MSBuild tasks you want, grouped into targets. It can also have property groups, item groups, and whatever else MSBuild supports.
To integrate into Visual Studio you add specially named targets that invoke what you want. Here you can see I've defined the BeforeClean and AfterBuild targets. You can get the supported targets from the VS integration docs.
Now, when I build or rebuild, a new directory containing the product DLL and a bunch of static files is automatically created, ready to zip up. If I wanted I could add the Nuget package for MSBuild Community Extensions and use the Zip task to bundle the whole thing into a zip file at the end too.
BTW, while you can define properties in your .targets files it's better to define them in property sheets instead. That way they're visible in the UI.
I'm using VS2010 Pro, and it doesn't expose the AfterBuild target, at least in C++ projects which is what I'm doing. As you see, it does have the "Events", which according to what I've read are for backward compatibility with converted projects from VSBuild. I agree, a MSBuild task rather than a command script is the way to go.
Forget the UI. It's made to support free editing of the XML files, and continue using the UI too as it respects what you had in there and uses labels for its own stuff so it can find it to update it.
But to keep it neat, you could use a property page; a stand-alone XML file with *.props name, and put what you want in it. Then add that props file to the projects using the UI. You won't hand-edit the project file that the UI is maintaining, and it won't touch the props file unless you go through the property manager view and open it explicitly.
Oh, I also recall seeing additional standard targets something like Package and Publish. Maybe those are not used on your project type, but you could use those entry points anyway.

Show only excluded files in VS2010

Is there any way (plugins / extensions are perfectly fine) to show ONLY items that are excluded from a project / solution?
I have a project in which I've just done some significant refactoring and several files and folders are no longer needed. Now I want to remove them from source control (Mercurial, VisualHG plugin is installed in VS2010). It's a rather large solution so I'd rather not have to manually drill through Solution Explorer to find them.
Or, if someone has another process to do this I'm certainly open to that as well.
Theres no existing addon at the moment. As the project files are XML (see below), in theory you could write an app to parse it and then compare it to the contents of the project directory; and enumerate each one gathering a list of items that are not included.
<ItemGroup>
<Content Include="rootFile.html" />
<Content Include="Directory1\File1.xml" />
<Content Include="Directory2\File2.xml" />
<ItemGroup>
As for integrating this behaviour into Visual Studio, either file a feature request with Microsoft or write this addon.

Exclude files from web site publish in Visual Studio

Can I exclude a folder or files when I publish a web site in Visual Studio 2005? I have various resources that I want to keep at hand in the Solution Explorer, such as alternate config files for various environments, but I don't really want to publish them to the server. Is there some way to exclude them? When using other project types, such as a .dll assembly, I can set a file's Build Action property to "None" and its Copy to Output Directory property to "Do not copy". I cannot find any similar settings for files in a web site.
If the IDE does not offer this feature, does anyone have good technique for handling such files?
Exclude files and folders by adding ExcludeFilesFromDeployment and ExcludeFoldersFromDeployment elements to your project file (.csproj, .vbproj, etc). You will need to edit the file in a text editor, or in Visual Studio by unloading the project and then editing it.
Add the tags anywhere within the appropriate PropertyGroup (Debug, Release, etc) as shown below:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
...
<ExcludeFilesFromDeployment>File1.aspx;Folder2\File2.aspx</ExcludeFilesFromDeployment>
<ExcludeFilesFromDeployment>**\.svn\**\*.*</ExcludeFilesFromDeployment>
<ExcludeFoldersFromDeployment>Folder1;Folder2\Folder2a</ExcludeFoldersFromDeployment>
</PropertyGroup>
Wildcards are supported.
To explain the example above:
The 1st ExcludeFilesFromDeployment excludes File1.aspx (in root of project) and Folder2\File2.aspx (Folder2 is in the root of the project)
The 2nd ExcludeFilesFromDeployment excludes all files within any folder named .svn and any of its subfolders
The ExcludeFoldersFromDeployment excludes folders named Folder1 (in root of project) and Folder2\Folder2a (Folder2 is in the root of the project)
For more info see MSDN blog post Web Deployment: Excluding Files and Folders via the Web Application’s Project File
Amazingly the answer for Visual Studio 2012 is not here:
The answer with green checkmark is not the answer.
The highest "upped" answer references an article from 2010 and says you have to edit your csproj project file which is now incorrect. I added the ExcludeFoldersFromDeployment XML element to my Visual Studio 2012 csproj file and it did nothing, the element was considered invalid, this is because ExcludeFoldersFromDeployment has been moved to the .pubxml file it looks like.
For Web Applications and Websites you edit the .pubxml file!
You can follow my answer or try this guide which I found later:
http://www.leniel.net/2014/05/using-msdeploy-publish-profile-pubxml-to-create-an-empty-folder-structure-on-iis-and-skip-deleting-it-with-msdeployskiprules.html#sthash.MSsQD8U1.dpbs
Yes, you can do this not just for Website Projects but Websites too. I spent a long time on the internet looking for this elusive exclude ability with a Visual Studio Website (NOT Website project) and had previously concluded it was not possible but it looks like it is:
In your [mypublishwebsitename].pubxml file, found in ~/Properties/PublishProfiles for Web Application Projects and ~/App_Data/PublishProfiles for Websites, simply add:
<ExcludeFilesFromDeployment>File1.aspx;Folder2\File2.aspx</ExcludeFilesFromDeployment>
<ExcludeFoldersFromDeployment>Folder1;Folder2\Folder2a</ExcludeFoldersFromDeployment>
as children to the main <PropertyGroup> element in your .pubxml file. No need to add a new element not unless you are keying a specific build type, like release or debug.
BUT WAIT!!!
If you are removing files from your destination/target server with the following setting in your Publish configuration:
Then the Web Publish process will delete on your source/target server anything excluded, like an item you have delineated in your <ExcludeFoldersFromDeployment> and <ExcludeFilesFromDeployment>!
MsDeploy Skip Rules to the rescue:
First, Web Publish uses something other than MSBuild to publish (called Task IO or something like that) but it has a bug and will not recognize skip rules, so you must add to your .pubxml:
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
</PropertyGroup>
I would keep <WebPublishMethod> in its own <PropertyGroup>, you would think you could just have one <PropertyGroup> element in your .pubxml but my Skip Rules were not being called until I moved <WebPublishMethod> to its own <PropertyGroup> element. Yes, crazy, but the fact you need to do all this for Web Publish to exclude and also not delete a folder/file on your server is crazy.
Now my actual SkipRules, ExcludeFolders and ExcludeFiles declarations in my .pubxml:
<ExcludeFoldersFromDeployment>Config</ExcludeFoldersFromDeployment>
<ExcludeFoldersFromDeployment>Photos</ExcludeFoldersFromDeployment>
<ExcludeFoldersFromDeployment>Temp</ExcludeFoldersFromDeployment>
<ExcludeFilesFromDeployment>Web.config</ExcludeFilesFromDeployment>
<AfterAddIisSettingAndFileContentsToSourceManifest>AddCustomSkipRules</AfterAddIisSettingAndFileContentsToSourceManifest>
And now a the Skip Rules (<Target> is a child of <Project> in your .pubxml):
(You may be able to leave <SkipAction> empty to Skip for all actions but I didn't test that and am not sure.
<Target Name="AddCustomSkipRules">
<Message Text="Adding Custom Skip Rules" />
<ItemGroup>
<MsDeploySkipRules Include="SkipConfigFolder">
<SkipAction>Delete</SkipAction>
<ObjectName>dirPath</ObjectName>
<AbsolutePath>$(_DestinationContentPath)\\Config</AbsolutePath>
<XPath>
</XPath>
</MsDeploySkipRules>
<MsDeploySkipRules Include="SkipPhotosFolder">
<SkipAction>Delete</SkipAction>
<ObjectName>dirPath</ObjectName>
<AbsolutePath>$(_DestinationContentPath)\\Photos</AbsolutePath>
<XPath>
</XPath>
</MsDeploySkipRules>
<MsDeploySkipRules Include="SkipWebConfig">
<SkipAction>Delete</SkipAction>
<ObjectName>filePath</ObjectName>
<AbsolutePath>$(_DestinationContentPath)\\Web\.config</AbsolutePath>
<XPath>
</XPath>
</MsDeploySkipRules>
<MsDeploySkipRules Include="SkipWebConfig">
<SkipAction>Delete</SkipAction>
<ObjectName>dirPath</ObjectName>
<AbsolutePath>$(_DestinationContentPath)\\Temp</AbsolutePath>
<XPath>
</XPath>
</MsDeploySkipRules>
</ItemGroup>
</Target>
And please, do not to forget to escape the . in a filePath Skip rule with a backslash.
If you can identify the files based on extension, you can configure this using the buildproviders tag in the web.config. Add the extension and map it to the ForceCopyBuildProvider. For example, to configure .xml files to be copied with a publish action, you would do the following:
<configuration>...
<system.web>...
<compilation>...
<buildProviders>
<remove extension=".xml" />
<add extension=".xml" type="System.Web.Compilation.ForceCopyBuildProvider" />
</buildProviders>
To keep a given file from being copied, you'd do the same thing but use System.Web.Compilation.IgnoreFileBuildProvider as the type.
I struggled with the same issue and finally pulled the trigger on converting the web site to a web application. Once I did this, I got all of the IDE benefits such as build action, and it compiled faster to boot (no more validating web site...).
Step 1: Convert your 'web site' to a 'web application'. To convert it I just created a new "web application", blew away all the files it created automatically, and copied and pasted my web site in. This worked fine. Note that report files will need to have their Build Action set to "Content" instead of "none".
Step 2: Now you can set any files "Build Action" property.
Hope this helps.
In Visual Studio 2013 I found Keith's answer, adding the ExcludeFoldersFromDeployment element to the project file, didn't work (I hadn't read Brian Ogden's answer which says this). However, I found I could exclude a text file when publishing in Visual Studio 2013 by just setting the following properties on the text file itself:
1) Build Action: None
2) Copy to Output Directory: Do not copy
Initially I tried setting the Copy to Output Directory property by itself but that didn't work when the Build Action was set to the default value, Content. When I then set the Build Action to None the text file was no longer copied to the destination folder when I published.
To view these properties in the Visual Studio GUI, in the Solution Explorer right-click on the file you want to exclude and select Properties from the context menu.
I think you only have two options here:
Use the 'Exclude From Project'
feature. This isn't ideal because the
project item will be excluded from
any integrated IDE source control operations.
You would need to click the 'Show All
Files' button on the Solution window
if you need to see the files in
Solution Explorer, but that also
shows files and folders you're not
interested in.
Use a post-build event script to
remove any project items you don't
want to be published (assuming you're
publishing to a local folder then
uploading to the server).
I've been through this before and couldn't come up with anything really elegant.
For Visual Studio 2017, WebApp Publish, first create a standard file system publish profile.
Go to the App_Data\PublishProfiles\ folder and edit the [profilename].pubxml file.
Add
<ExcludeFilesFromDeployment>[file1.ext];[file2.ext];[file(n).ext]</ExcludeFilesFromDeployment>
under the tag<PropertyGroup>
You can only specify this tag once, otherwise it will only take the last one's values.
Example:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>FileSystem</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<ExcludeApp_Data>True</ExcludeApp_Data>
<publishUrl>C:\inetput\mysite</publishUrl>
<DeleteExistingFiles>False</DeleteExistingFiles>
<ExcludeFilesFromDeployment>web.config;mysite.sln;App_Code\DevClass.cs;</ExcludeFilesFromDeployment>
</PropertyGroup>
</Project>
Make sure that the tag DeleteExistingFiles is set to False
As a contemporary answer, in Visual Studio 2017 with a .net core site:
You can exclude from publish like so in the csproj, where CopyToPublishDirectory is never.
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Update="appsettings.Local.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</Content>
</ItemGroup>
This is discussed in more detail here: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/visual-studio-publish-profiles?view=aspnetcore-2.2
<PropertyGroup>
<ExcludeFilesFromDeployment>appsettings.Local.json</ExcludeFilesFromDeployment>
</PropertyGroup>
The earlier suggestions did not work for me, I'm guessing because visual studio is now using a different publishing mechanism underneath, I presume via the "dotnet publish" cli tool or equivalent underneath.
The feature you are looking exists if your project is created as a "Web Application". Web Site "projects" are just a collection of files that are thought of as 1:1 with what gets deployed to a web server.
In terms of functionality both are the same, however a web application compiles all source code to a DLL, instead of the naked source code files being copied to the web server and compiled as needed.
This is just an addendum to the other helpful answers here and something I've found useful...
Using wpp.targets to excluded files and folders
When you have multiple deployments for different environments then it's helpful to have just one common file where you can set all the excluded files and folders. You can do this by creating a *.wpp.targets file in the root of the project like the example below.
For more information see this Microsoft guide:
How to: Edit Deployment Settings in Publish Profile (.pubxml) Files and the .wpp.targets File in Visual Studio Web Projects
<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EnableMSDeployAppOffline>True</EnableMSDeployAppOffline>
<ExcludeFilesFromDeployment>
*.config;
*.targets;
*.default;
</ExcludeFilesFromDeployment>
<ExcludeFoldersFromDeployment>
images;
videos;
uploads;
</ExcludeFoldersFromDeployment>
</PropertyGroup>
</Project>
In Visual Studio 2017 (15.9.3 in my case) the manipulation of the .csproj-File works fine indeed! No need to modify the pubxml.
You can then construct pretty nice settings in the .csproj-File using the PropertyGroup condition, e.g.:
<PropertyGroup Condition="$(Configuration.StartsWith('Pub_'))">
<ExcludeFoldersFromDeployment>Samples</ExcludeFoldersFromDeployment>
</PropertyGroup>
excludes the "Samples" folder from all deployments with configurations starting with "Pub_"...
In Visual Studio 2022 I have successfully used this settings:
Go and edit the
[ProjectName] \ Properties \ PublishProfiles \ FolderProfile.pubxml file
in solution explorer.
Add these lines inside PropertyGroup
element:
<ItemGroup>
<Content Remove="Data\*.json" />
<None Include="Data\*.json" />
</ItemGroup>
Then save the .pubxml file and try to publish the project.
"Content Remove" will remove the file from the content to deploy.
"None Include" will keep the file in the solution explorer.
It's possible to set it up in the solution explorer for single files as well: right click the file in the solution explorer -> Properties and change the Build Action to None.

Resources