728x90
트리뷰에서 xml파일 추가 버튼을 클릭하면 xml파일이 생성되도록 구현
- 파일명을 받아 줄 View를 추가 및 확인 버튼 클릭이벤트 추가
<Label Grid.Row="0" Grid.Column="0" Content="파일명을 입력하세요." HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBox Grid.Row="1" x:Name="fileNameTextBox" VerticalAlignment="Center" Margin="3" Padding="5 5 5 5"/>
...
<Button Grid.Column="1" Content="확인" HorizontalAlignment="Stretch" VerticalAlignment="Center" Click="OKButton_Click" Width="30" Margin="3" RenderTransformOrigin="1.857,0.546"/>
<Button Grid.Column="2" Content="취소" HorizontalAlignment="Right" VerticalAlignment="Center" Click="CancelButton_Click" Width="30" Margin="3"/>
</Grid>
private void OKButton_Click(object sender, RoutedEventArgs e)
{
string enteredFileName = fileNameTextBox.Text;
if (enteredFileName == "")
{
MessageBox.Show("파일명을 입력해주세요.");
} else
{
EnteredFileName = enteredFileName;
Close(); // 창 닫기
}
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
Close(); // 창 닫기
}
- 파일 추가 버튼 클릭 시 이벤트 (xml파일 생성) 추가
private void PlusButton_Click(object sender, RoutedEventArgs e)
{
// 모달 생성
FileAddView EnteredFileName = new FileAddView();
// 모달 띄우고 파일 이름 입력 받기
EnteredFileName.Owner = Application.Current.MainWindow;
EnteredFileName.WindowStartupLocation = WindowStartupLocation.CenterOwner;
bool? dialogResult = EnteredFileName.ShowDialog();
string result = EnteredFileName.EnteredFileName;
if (dialogResult.HasValue)
{
string fileName = EnteredFileName.EnteredFileName;
// 파일 이름이 유효하면 이어서 작업을 수행
if (!string.IsNullOrWhiteSpace(fileName))
{
// 현재 선택된 TreeViewItem 가져오기
TreeViewItem selectedItem = treeView.SelectedItem as TreeViewItem;
if (selectedItem != null)
{
// 새 XML 파일 경로 생성
string filePath = QueryTreeViewModel.GetFolderPathFromTree(selectedItem, fileName);
string projectPath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;
// XML 파일 생성 및 초기화
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
// 루트 엘리먼트 추가
XmlElement rootElement = xmlDoc.CreateElement(fileName);
xmlDoc.AppendChild(rootElement);
// XML 파일 저장
xmlDoc.Save(projectPath + filePath);
// TreeView에 새 파일 노드 추가
TreeViewItem fileNode = new TreeViewItem();
fileNode.Header = fileName + ".xml";
selectedItem.Items.Add(fileNode);
}
}
}
else
{
MessageBox.Show("파일 생성 실패");
}
파일경로 생성 시 GetFolderPathFromTree 메서드
//선택된 노드의 폴더경로
public string GetFolderPathFromTree(TreeViewItem selectedItem, string fileName)
{
string path = "\\Models\\";
string filePath = "";
string tmp = selectedItem.Header.ToString();
while (selectedItem != null)
{
// 각 노드의 헤더 문자열을 경로에 추가
filePath = Path.Combine(selectedItem.Header.ToString(), filePath);
selectedItem = selectedItem.Parent as TreeViewItem;
}
if (tmp.Contains(".xml"))
{
filePath = filePath.Replace(tmp, "");
}
filePath = Path.Combine(filePath, fileName)+".xml";
return path+filePath;
}
트리뷰에서 폴더를 선택하면 가장 좋겠지만 보통은 가장 하위노드를 클릭 한 상태로 파일 추가를 하는 경우도 있기 때문에,
가장 하위노드(.xml이 들어간 경우)를 선택 한 경우 해당 이름을 Path에서 빼버린다.
애먹은 부분은 xml파일을 저장해주는 xmlDoc.Save(projectPath + filePath); 이 부분인데, 프로젝트 경로부터 해당 파일을 생성하는 경로 + 파일이름까지 싹다 들어가야한다. 아니면 계속 오류 뜨거나 Path에서 " \bin\Debug " 가 들어가서 오류가 난다.
코드가 모두 실행되면 해당 경로에 xml파일이 생긴다.
해당 작업 완료 후 참고하면 좋은글
2023.09.19 - [C#/C# WPF 실무] - [C# WPF] 외부에서 만들어진 파일 비주얼 스튜디오에서 확인 안될 때
[C# WPF] 외부에서 만들어진 파일 비주얼 스튜디오에서 확인 안될 때
비주얼스튜디오는 프로젝트 경로에서 파일 추가 시 프로그램 안에서 해당 파일이 안보인다. 솔루션 탐색기에서 모든파일 표시 아이콘 클릭 내가 추가했던 파일 경로로 가보면 이런 점선 파일이
sm-lee2026210.tistory.com
728x90
'C# > C# WPF 실무' 카테고리의 다른 글
[C# WPF] xml파일 생성하기 (0) | 2023.09.19 |
---|---|
[C# WPF] 외부에서 만들어진 파일 비주얼 스튜디오에서 확인 안될 때 (0) | 2023.09.19 |
[C# WPF] 복사하기 버튼을 통해 복사하기 (0) | 2023.09.18 |
[C# WPF] TreeView 아이콘 적용 및 하위노드 더블클릭 시 이벤트 발생 (0) | 2023.09.18 |
[C# WPF] 프로젝트 내 폴더로 파일 탐색기 만들기 (0) | 2023.09.13 |