diff --git a/lean/commands/library/add.py b/lean/commands/library/add.py
index 8dbebfe7..68dd7b83 100644
--- a/lean/commands/library/add.py
+++ b/lean/commands/library/add.py
@@ -70,7 +70,7 @@ def _add_csharp_package_to_csproj(csproj_file: Path, name: str, version: str) ->
else:
last_item_group = csproj_tree.find(".//ItemGroup[last()]")
if last_item_group is None:
- last_item_group = etree.SubElement(csproj_tree.find(".//Project"), "ItemGroup")
+ last_item_group = etree.SubElement(csproj_tree, "ItemGroup")
last_item_group.append(etree.fromstring(f''))
diff --git a/lean/components/util/library_manager.py b/lean/components/util/library_manager.py
index d3024ed8..93e45887 100644
--- a/lean/components/util/library_manager.py
+++ b/lean/components/util/library_manager.py
@@ -280,7 +280,7 @@ def _add_csharp_project_to_csproj(self, csproj_file: Path, library_csproj_path:
if existing_project_reference is None:
last_item_group = csproj_tree.find(".//ItemGroup[last()]")
if last_item_group is None:
- last_item_group = etree.SubElement(csproj_tree.find(".//Project"), "ItemGroup")
+ last_item_group = etree.SubElement(csproj_tree, "ItemGroup")
last_item_group.append(etree.fromstring(f''))
diff --git a/tests/components/util/test_library_manager.py b/tests/components/util/test_library_manager.py
index 92382d76..e356a954 100644
--- a/tests/components/util/test_library_manager.py
+++ b/tests/components/util/test_library_manager.py
@@ -168,3 +168,17 @@ def test_detects_circular_dependencies() -> None:
assert False, "Expected library_manager.add_lean_library_reference_to_project() to raise on circular dependency"
except RuntimeError:
pass
+
+
+def test_add_csharp_project_to_csproj_without_item_group_adds_reference() -> None:
+ create_fake_lean_cli_directory()
+
+ csproj_file = Path.cwd() / "Empty.csproj"
+ csproj_file.write_text('\n \n', encoding="utf-8")
+
+ library_manager = _create_library_manager()
+ library_manager._add_csharp_project_to_csproj(csproj_file, "../Library/Lib/Lib.csproj")
+
+ content = csproj_file.read_text(encoding="utf-8")
+ assert '") == 1