SftpTests.cs 236 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. [DataTestMethod]
  24. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  25. public void Sftp_UploadFile_FileStream(int size)
  26. {
  27. var file = CreateTempFile(size);
  28. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  30. {
  31. client.Connect();
  32. var remoteFile = GenerateUniqueRemoteFileName();
  33. if (client.Exists(remoteFile))
  34. {
  35. client.Delete(remoteFile);
  36. }
  37. try
  38. {
  39. client.UploadFile(fs, remoteFile);
  40. using (var memoryStream = new MemoryStream(size))
  41. {
  42. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  43. memoryStream.Position = 0;
  44. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  45. }
  46. }
  47. finally
  48. {
  49. if (client.Exists(remoteFile))
  50. {
  51. client.Delete(remoteFile);
  52. }
  53. }
  54. }
  55. }
  56. [TestMethod]
  57. public void Sftp_ConnectDisconnect_Serial()
  58. {
  59. const int iterations = 100;
  60. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  61. {
  62. for (var i = 1; i <= iterations; i++)
  63. {
  64. client.Connect();
  65. client.Disconnect();
  66. }
  67. }
  68. }
  69. [TestMethod]
  70. public void Sftp_ConnectDisconnect_Parallel()
  71. {
  72. const int iterations = 10;
  73. const int threads = 5;
  74. var startEvent = new ManualResetEvent(false);
  75. var tasks = Enumerable.Range(1, threads).Select(i =>
  76. {
  77. return Task.Factory.StartNew(() =>
  78. {
  79. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  80. {
  81. startEvent.WaitOne();
  82. for (var j = 0; j < iterations; j++)
  83. {
  84. client.Connect();
  85. client.Disconnect();
  86. }
  87. }
  88. });
  89. }).ToArray();
  90. startEvent.Set();
  91. Task.WaitAll(tasks);
  92. }
  93. [TestMethod]
  94. public void Sftp_BeginUploadFile()
  95. {
  96. const string content = "SftpBeginUploadFile";
  97. var expectedByteCount = (ulong)Encoding.ASCII.GetByteCount(content);
  98. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  99. {
  100. client.Connect();
  101. var remoteFile = GenerateUniqueRemoteFileName();
  102. if (client.Exists(remoteFile))
  103. {
  104. client.Delete(remoteFile);
  105. }
  106. try
  107. {
  108. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  109. {
  110. IAsyncResult asyncResultCallback = null;
  111. using var callbackCalled = new ManualResetEventSlim(false);
  112. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar =>
  113. {
  114. asyncResultCallback = ar;
  115. callbackCalled.Set();
  116. });
  117. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  118. // check async result
  119. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  120. Assert.IsNotNull(sftpUploadAsyncResult);
  121. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  122. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  123. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  124. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  125. Assert.IsTrue(callbackCalled.Wait(10000));
  126. // check async result callback
  127. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  128. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  129. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  130. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  131. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  132. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  133. }
  134. // check uploaded file
  135. using (var memoryStream = new MemoryStream())
  136. {
  137. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  138. memoryStream.Position = 0;
  139. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  140. Assert.AreEqual(content, remoteContent);
  141. }
  142. }
  143. finally
  144. {
  145. if (client.Exists(remoteFile))
  146. {
  147. client.Delete(remoteFile);
  148. }
  149. }
  150. }
  151. }
  152. [TestMethod]
  153. public void Sftp_Create_ExistingFile()
  154. {
  155. var encoding = Encoding.UTF8;
  156. var initialContent = "Gert & Ann & Lisa";
  157. var newContent1 = "Sofie";
  158. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  159. var newContent2 = "Lisa & Sofie";
  160. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  162. {
  163. client.Connect();
  164. var remoteFile = GenerateUniqueRemoteFileName();
  165. if (client.Exists(remoteFile))
  166. {
  167. client.DeleteFile(remoteFile);
  168. }
  169. try
  170. {
  171. client.WriteAllText(remoteFile, initialContent);
  172. #region Write less bytes than the current content, overwriting part of that content
  173. using (var fs = client.Create(remoteFile))
  174. using (var sw = new StreamWriter(fs, encoding))
  175. {
  176. sw.Write(newContent1);
  177. }
  178. var actualContent1 = client.ReadAllBytes(remoteFile);
  179. Assert.IsTrue(newContent1Bytes.IsEqualTo(actualContent1));
  180. #endregion Write less bytes than the current content, overwriting part of that content
  181. #region Write more bytes than the current content, overwriting and appending to that content
  182. using (var fs = client.Create(remoteFile))
  183. using (var sw = new StreamWriter(fs, encoding))
  184. {
  185. sw.Write(newContent2);
  186. }
  187. var actualContent2 = client.ReadAllBytes(remoteFile);
  188. Assert.IsTrue(newContent2Bytes.IsEqualTo(actualContent2));
  189. #endregion Write more bytes than the current content, overwriting and appending to that content
  190. }
  191. finally
  192. {
  193. if (client.Exists(remoteFile))
  194. {
  195. client.DeleteFile(remoteFile);
  196. }
  197. }
  198. }
  199. }
  200. [TestMethod]
  201. public void Sftp_Create_DirectoryDoesNotExist()
  202. {
  203. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  204. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  205. {
  206. client.Connect();
  207. if (client.Exists(remoteFile))
  208. {
  209. client.DeleteFile(remoteFile);
  210. }
  211. SftpFileStream fs = null;
  212. try
  213. {
  214. fs = client.Create(remoteFile);
  215. Assert.Fail();
  216. }
  217. catch (SftpPathNotFoundException ex)
  218. {
  219. Assert.IsNull(ex.InnerException);
  220. Assert.AreEqual("No such file", ex.Message);
  221. }
  222. finally
  223. {
  224. fs?.Dispose();
  225. if (client.Exists(remoteFile))
  226. {
  227. client.DeleteFile(remoteFile);
  228. }
  229. }
  230. }
  231. }
  232. [TestMethod]
  233. public void Sftp_Create_FileDoesNotExist()
  234. {
  235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  236. {
  237. client.BufferSize = 512 * 1024;
  238. client.Connect();
  239. var remoteFile = GenerateUniqueRemoteFileName();
  240. if (client.Exists(remoteFile))
  241. {
  242. client.DeleteFile(remoteFile);
  243. }
  244. try
  245. {
  246. using (var imageStream = GetData("resources.issue #70.png"))
  247. {
  248. using (var fs = client.Create(remoteFile))
  249. {
  250. imageStream.CopyTo(fs);
  251. }
  252. using (var memoryStream = new MemoryStream())
  253. {
  254. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  255. memoryStream.Position = 0;
  256. imageStream.Position = 0;
  257. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  258. }
  259. }
  260. }
  261. finally
  262. {
  263. if (client.Exists(remoteFile))
  264. {
  265. client.DeleteFile(remoteFile);
  266. }
  267. }
  268. }
  269. }
  270. [TestMethod]
  271. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  272. {
  273. var initialContent = "\u0100ert & Ann";
  274. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  275. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  276. Environment.NewLine;
  277. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  278. {
  279. client.Connect();
  280. var remoteFile = GenerateUniqueRemoteFileName();
  281. if (client.Exists(remoteFile))
  282. {
  283. client.DeleteFile(remoteFile);
  284. }
  285. try
  286. {
  287. client.WriteAllText(remoteFile, initialContent);
  288. client.AppendAllLines(remoteFile, linesToAppend);
  289. var text = client.ReadAllText(remoteFile);
  290. Assert.AreEqual(expectedContent, text);
  291. // ensure we didn't write an UTF-8 BOM
  292. using (var fs = client.OpenRead(remoteFile))
  293. {
  294. var firstByte = fs.ReadByte();
  295. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  296. }
  297. }
  298. finally
  299. {
  300. if (client.Exists(remoteFile))
  301. {
  302. client.DeleteFile(remoteFile);
  303. }
  304. }
  305. }
  306. }
  307. [TestMethod]
  308. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  309. {
  310. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  311. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  312. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  313. {
  314. client.Connect();
  315. if (client.Exists(remoteFile))
  316. {
  317. client.DeleteFile(remoteFile);
  318. }
  319. try
  320. {
  321. client.AppendAllLines(remoteFile, linesToAppend);
  322. Assert.Fail();
  323. }
  324. catch (SftpPathNotFoundException ex)
  325. {
  326. Assert.IsNull(ex.InnerException);
  327. Assert.AreEqual("No such file", ex.Message);
  328. }
  329. finally
  330. {
  331. if (client.Exists(remoteFile))
  332. {
  333. client.DeleteFile(remoteFile);
  334. }
  335. }
  336. }
  337. }
  338. [TestMethod]
  339. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  340. {
  341. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  342. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  343. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  344. {
  345. client.Connect();
  346. var remoteFile = GenerateUniqueRemoteFileName();
  347. if (client.Exists(remoteFile))
  348. {
  349. client.DeleteFile(remoteFile);
  350. }
  351. try
  352. {
  353. client.AppendAllLines(remoteFile, linesToAppend);
  354. var text = client.ReadAllText(remoteFile);
  355. Assert.AreEqual(expectedContent, text);
  356. // ensure we didn't write an UTF-8 BOM
  357. using (var fs = client.OpenRead(remoteFile))
  358. {
  359. var firstByte = fs.ReadByte();
  360. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  361. }
  362. }
  363. finally
  364. {
  365. if (client.Exists(remoteFile))
  366. {
  367. client.DeleteFile(remoteFile);
  368. }
  369. }
  370. }
  371. }
  372. [TestMethod]
  373. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  374. {
  375. var initialContent = "\u0100ert & Ann";
  376. var contentToAppend = "Forever&\u0116ver";
  377. var expectedContent = initialContent + contentToAppend;
  378. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  379. {
  380. client.Connect();
  381. var remoteFile = GenerateUniqueRemoteFileName();
  382. if (client.Exists(remoteFile))
  383. {
  384. client.DeleteFile(remoteFile);
  385. }
  386. try
  387. {
  388. client.WriteAllText(remoteFile, initialContent);
  389. client.AppendAllText(remoteFile, contentToAppend);
  390. var text = client.ReadAllText(remoteFile);
  391. Assert.AreEqual(expectedContent, text);
  392. // ensure we didn't write an UTF-8 BOM
  393. using (var fs = client.OpenRead(remoteFile))
  394. {
  395. var firstByte = fs.ReadByte();
  396. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  397. }
  398. }
  399. finally
  400. {
  401. if (client.Exists(remoteFile))
  402. {
  403. client.DeleteFile(remoteFile);
  404. }
  405. }
  406. }
  407. }
  408. [TestMethod]
  409. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  410. {
  411. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  412. var contentToAppend = "Forever&\u0116ver";
  413. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  414. {
  415. client.Connect();
  416. if (client.Exists(remoteFile))
  417. {
  418. client.DeleteFile(remoteFile);
  419. }
  420. try
  421. {
  422. client.AppendAllText(remoteFile, contentToAppend);
  423. Assert.Fail();
  424. }
  425. catch (SftpPathNotFoundException ex)
  426. {
  427. Assert.IsNull(ex.InnerException);
  428. Assert.AreEqual("No such file", ex.Message);
  429. }
  430. finally
  431. {
  432. if (client.Exists(remoteFile))
  433. {
  434. client.DeleteFile(remoteFile);
  435. }
  436. }
  437. }
  438. }
  439. [TestMethod]
  440. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  441. {
  442. var contentToAppend = "Forever&\u0116ver";
  443. var expectedContent = contentToAppend;
  444. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  445. {
  446. client.Connect();
  447. var remoteFile = GenerateUniqueRemoteFileName();
  448. if (client.Exists(remoteFile))
  449. {
  450. client.DeleteFile(remoteFile);
  451. }
  452. try
  453. {
  454. client.AppendAllText(remoteFile, contentToAppend);
  455. var text = client.ReadAllText(remoteFile);
  456. Assert.AreEqual(expectedContent, text);
  457. // ensure we didn't write an UTF-8 BOM
  458. using (var fs = client.OpenRead(remoteFile))
  459. {
  460. var firstByte = fs.ReadByte();
  461. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  462. }
  463. }
  464. finally
  465. {
  466. if (client.Exists(remoteFile))
  467. {
  468. client.DeleteFile(remoteFile);
  469. }
  470. }
  471. }
  472. }
  473. [TestMethod]
  474. public void Sftp_AppendText_NoEncoding_ExistingFile()
  475. {
  476. var initialContent = "\u0100ert & Ann";
  477. var contentToAppend = "Forever&\u0116ver";
  478. var expectedContent = initialContent + contentToAppend;
  479. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  480. {
  481. client.Connect();
  482. var remoteFile = GenerateUniqueRemoteFileName();
  483. if (client.Exists(remoteFile))
  484. {
  485. client.DeleteFile(remoteFile);
  486. }
  487. try
  488. {
  489. client.WriteAllText(remoteFile, initialContent);
  490. using (var sw = client.AppendText(remoteFile))
  491. {
  492. sw.Write(contentToAppend);
  493. }
  494. var text = client.ReadAllText(remoteFile);
  495. Assert.AreEqual(expectedContent, text);
  496. // ensure we didn't write an UTF-8 BOM
  497. using (var fs = client.OpenRead(remoteFile))
  498. {
  499. var firstByte = fs.ReadByte();
  500. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  501. }
  502. }
  503. finally
  504. {
  505. if (client.Exists(remoteFile))
  506. {
  507. client.DeleteFile(remoteFile);
  508. }
  509. }
  510. }
  511. }
  512. [TestMethod]
  513. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  514. {
  515. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  516. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  517. {
  518. client.Connect();
  519. if (client.Exists(remoteFile))
  520. {
  521. client.DeleteFile(remoteFile);
  522. }
  523. StreamWriter sw = null;
  524. try
  525. {
  526. sw = client.AppendText(remoteFile);
  527. Assert.Fail();
  528. }
  529. catch (SftpPathNotFoundException ex)
  530. {
  531. Assert.IsNull(ex.InnerException);
  532. Assert.AreEqual("No such file", ex.Message);
  533. }
  534. finally
  535. {
  536. sw?.Dispose();
  537. if (client.Exists(remoteFile))
  538. {
  539. client.DeleteFile(remoteFile);
  540. }
  541. }
  542. }
  543. }
  544. [TestMethod]
  545. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  546. {
  547. var contentToAppend = "\u0100ert & Ann";
  548. var expectedContent = contentToAppend;
  549. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  550. {
  551. client.Connect();
  552. var remoteFile = GenerateUniqueRemoteFileName();
  553. if (client.Exists(remoteFile))
  554. {
  555. client.DeleteFile(remoteFile);
  556. }
  557. try
  558. {
  559. using (var sw = client.AppendText(remoteFile))
  560. {
  561. sw.Write(contentToAppend);
  562. }
  563. // ensure we didn't write an UTF-8 BOM
  564. using (var fs = client.OpenRead(remoteFile))
  565. {
  566. var firstByte = fs.ReadByte();
  567. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  568. }
  569. }
  570. finally
  571. {
  572. if (client.Exists(remoteFile))
  573. {
  574. client.DeleteFile(remoteFile);
  575. }
  576. }
  577. }
  578. }
  579. [TestMethod]
  580. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  581. {
  582. var initialContent = "\u0100ert & Ann";
  583. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  584. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  585. Environment.NewLine;
  586. var encoding = GetRandomEncoding();
  587. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  588. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  589. {
  590. client.Connect();
  591. var remoteFile = GenerateUniqueRemoteFileName();
  592. if (client.Exists(remoteFile))
  593. {
  594. client.DeleteFile(remoteFile);
  595. }
  596. try
  597. {
  598. client.WriteAllText(remoteFile, initialContent, encoding);
  599. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  600. var text = client.ReadAllText(remoteFile, encoding);
  601. Assert.AreEqual(expectedContent, text);
  602. using (var fs = client.OpenRead(remoteFile))
  603. {
  604. var actualBytes = new byte[fs.Length];
  605. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  606. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  607. }
  608. }
  609. finally
  610. {
  611. if (client.Exists(remoteFile))
  612. {
  613. client.DeleteFile(remoteFile);
  614. }
  615. }
  616. }
  617. }
  618. [TestMethod]
  619. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  620. {
  621. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  622. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  623. var encoding = GetRandomEncoding();
  624. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  625. {
  626. client.Connect();
  627. if (client.Exists(remoteFile))
  628. {
  629. client.DeleteFile(remoteFile);
  630. }
  631. try
  632. {
  633. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  634. Assert.Fail();
  635. }
  636. catch (SftpPathNotFoundException ex)
  637. {
  638. Assert.IsNull(ex.InnerException);
  639. Assert.AreEqual("No such file", ex.Message);
  640. }
  641. finally
  642. {
  643. if (client.Exists(remoteFile))
  644. {
  645. client.DeleteFile(remoteFile);
  646. }
  647. }
  648. }
  649. }
  650. [TestMethod]
  651. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  652. {
  653. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  654. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  655. var encoding = GetRandomEncoding();
  656. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  657. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  658. {
  659. client.Connect();
  660. var remoteFile = GenerateUniqueRemoteFileName();
  661. if (client.Exists(remoteFile))
  662. {
  663. client.DeleteFile(remoteFile);
  664. }
  665. try
  666. {
  667. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  668. var text = client.ReadAllText(remoteFile, encoding);
  669. Assert.AreEqual(expectedContent, text);
  670. using (var fs = client.OpenRead(remoteFile))
  671. {
  672. var actualBytes = new byte[fs.Length];
  673. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  674. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  675. }
  676. }
  677. finally
  678. {
  679. if (client.Exists(remoteFile))
  680. {
  681. client.DeleteFile(remoteFile);
  682. }
  683. }
  684. }
  685. }
  686. [TestMethod]
  687. public void Sftp_AppendAllText_Encoding_ExistingFile()
  688. {
  689. var initialContent = "\u0100ert & Ann";
  690. var contentToAppend = "Forever&\u0116ver";
  691. var expectedContent = initialContent + contentToAppend;
  692. var encoding = GetRandomEncoding();
  693. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  694. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  695. {
  696. client.Connect();
  697. var remoteFile = GenerateUniqueRemoteFileName();
  698. if (client.Exists(remoteFile))
  699. {
  700. client.DeleteFile(remoteFile);
  701. }
  702. try
  703. {
  704. client.WriteAllText(remoteFile, initialContent, encoding);
  705. client.AppendAllText(remoteFile, contentToAppend, encoding);
  706. var text = client.ReadAllText(remoteFile, encoding);
  707. Assert.AreEqual(expectedContent, text);
  708. using (var fs = client.OpenRead(remoteFile))
  709. {
  710. var actualBytes = new byte[fs.Length];
  711. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  712. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  713. }
  714. }
  715. finally
  716. {
  717. if (client.Exists(remoteFile))
  718. {
  719. client.DeleteFile(remoteFile);
  720. }
  721. }
  722. }
  723. }
  724. [TestMethod]
  725. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  726. {
  727. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  728. const string contentToAppend = "Forever&\u0116ver";
  729. var encoding = GetRandomEncoding();
  730. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  731. {
  732. client.Connect();
  733. if (client.Exists(remoteFile))
  734. {
  735. client.DeleteFile(remoteFile);
  736. }
  737. try
  738. {
  739. client.AppendAllText(remoteFile, contentToAppend, encoding);
  740. Assert.Fail();
  741. }
  742. catch (SftpPathNotFoundException ex)
  743. {
  744. Assert.IsNull(ex.InnerException);
  745. Assert.AreEqual("No such file", ex.Message);
  746. }
  747. finally
  748. {
  749. if (client.Exists(remoteFile))
  750. {
  751. client.DeleteFile(remoteFile);
  752. }
  753. }
  754. }
  755. }
  756. [TestMethod]
  757. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  758. {
  759. const string contentToAppend = "Forever&\u0116ver";
  760. var expectedContent = contentToAppend;
  761. var encoding = GetRandomEncoding();
  762. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  763. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  764. {
  765. client.Connect();
  766. var remoteFile = GenerateUniqueRemoteFileName();
  767. if (client.Exists(remoteFile))
  768. {
  769. client.DeleteFile(remoteFile);
  770. }
  771. try
  772. {
  773. client.AppendAllText(remoteFile, contentToAppend, encoding);
  774. var text = client.ReadAllText(remoteFile, encoding);
  775. Assert.AreEqual(expectedContent, text);
  776. using (var fs = client.OpenRead(remoteFile))
  777. {
  778. var actualBytes = new byte[fs.Length];
  779. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  780. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  781. }
  782. }
  783. finally
  784. {
  785. if (client.Exists(remoteFile))
  786. {
  787. client.DeleteFile(remoteFile);
  788. }
  789. }
  790. }
  791. }
  792. [TestMethod]
  793. public void Sftp_AppendText_Encoding_ExistingFile()
  794. {
  795. const string initialContent = "\u0100ert & Ann";
  796. const string contentToAppend = "Forever&\u0116ver";
  797. var expectedContent = initialContent + contentToAppend;
  798. var encoding = GetRandomEncoding();
  799. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  800. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  801. {
  802. client.Connect();
  803. var remoteFile = GenerateUniqueRemoteFileName();
  804. if (client.Exists(remoteFile))
  805. {
  806. client.DeleteFile(remoteFile);
  807. }
  808. try
  809. {
  810. client.WriteAllText(remoteFile, initialContent, encoding);
  811. using (var sw = client.AppendText(remoteFile, encoding))
  812. {
  813. sw.Write(contentToAppend);
  814. }
  815. var text = client.ReadAllText(remoteFile, encoding);
  816. Assert.AreEqual(expectedContent, text);
  817. using (var fs = client.OpenRead(remoteFile))
  818. {
  819. var actualBytes = new byte[fs.Length];
  820. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  821. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  822. }
  823. }
  824. finally
  825. {
  826. if (client.Exists(remoteFile))
  827. {
  828. client.DeleteFile(remoteFile);
  829. }
  830. }
  831. }
  832. }
  833. [TestMethod]
  834. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  835. {
  836. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  837. var encoding = GetRandomEncoding();
  838. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  839. {
  840. client.Connect();
  841. if (client.Exists(remoteFile))
  842. {
  843. client.DeleteFile(remoteFile);
  844. }
  845. StreamWriter sw = null;
  846. try
  847. {
  848. sw = client.AppendText(remoteFile, encoding);
  849. Assert.Fail();
  850. }
  851. catch (SftpPathNotFoundException ex)
  852. {
  853. Assert.IsNull(ex.InnerException);
  854. Assert.AreEqual("No such file", ex.Message);
  855. }
  856. finally
  857. {
  858. sw?.Dispose();
  859. if (client.Exists(remoteFile))
  860. {
  861. client.DeleteFile(remoteFile);
  862. }
  863. }
  864. }
  865. }
  866. [TestMethod]
  867. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  868. {
  869. var encoding = GetRandomEncoding();
  870. const string contentToAppend = "\u0100ert & Ann";
  871. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  872. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  873. {
  874. client.Connect();
  875. var remoteFile = GenerateUniqueRemoteFileName();
  876. if (client.Exists(remoteFile))
  877. {
  878. client.DeleteFile(remoteFile);
  879. }
  880. try
  881. {
  882. using (var sw = client.AppendText(remoteFile, encoding))
  883. {
  884. sw.Write(contentToAppend);
  885. }
  886. using (var fs = client.OpenRead(remoteFile))
  887. {
  888. var actualBytes = new byte[fs.Length];
  889. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  890. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  891. }
  892. }
  893. finally
  894. {
  895. if (client.Exists(remoteFile))
  896. {
  897. client.DeleteFile(remoteFile);
  898. }
  899. }
  900. }
  901. }
  902. [TestMethod]
  903. public void Sftp_CreateText_NoEncoding_ExistingFile()
  904. {
  905. var encoding = new UTF8Encoding(false, true);
  906. const string initialContent = "\u0100ert & Ann";
  907. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  908. const string newContent = "\u0116ver";
  909. const string expectedContent = "\u0116ver" + " & Ann";
  910. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  911. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  912. {
  913. client.Connect();
  914. var remoteFile = GenerateUniqueRemoteFileName();
  915. if (client.Exists(remoteFile))
  916. {
  917. client.DeleteFile(remoteFile);
  918. }
  919. try
  920. {
  921. client.WriteAllText(remoteFile, initialContent);
  922. using (client.CreateText(remoteFile))
  923. {
  924. }
  925. // verify that original content is left untouched
  926. using (var fs = client.OpenRead(remoteFile))
  927. {
  928. var actualBytes = new byte[fs.Length];
  929. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  930. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  931. }
  932. // write content that is less bytes than original content
  933. using (var sw = client.CreateText(remoteFile))
  934. {
  935. sw.Write(newContent);
  936. }
  937. // verify that original content is only partially overwritten
  938. var text = client.ReadAllText(remoteFile);
  939. Assert.AreEqual(expectedContent, text);
  940. using (var fs = client.OpenRead(remoteFile))
  941. {
  942. var actualBytes = new byte[fs.Length];
  943. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  944. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  945. }
  946. }
  947. finally
  948. {
  949. if (client.Exists(remoteFile))
  950. {
  951. client.DeleteFile(remoteFile);
  952. }
  953. }
  954. }
  955. }
  956. [TestMethod]
  957. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  958. {
  959. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  960. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  961. {
  962. client.Connect();
  963. if (client.Exists(remoteFile))
  964. {
  965. client.DeleteFile(remoteFile);
  966. }
  967. StreamWriter sw = null;
  968. try
  969. {
  970. sw = client.CreateText(remoteFile);
  971. Assert.Fail();
  972. }
  973. catch (SftpPathNotFoundException ex)
  974. {
  975. Assert.IsNull(ex.InnerException);
  976. Assert.AreEqual("No such file", ex.Message);
  977. }
  978. finally
  979. {
  980. sw?.Dispose();
  981. if (client.Exists(remoteFile))
  982. {
  983. client.DeleteFile(remoteFile);
  984. }
  985. }
  986. }
  987. }
  988. [TestMethod]
  989. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  990. {
  991. var encoding = new UTF8Encoding(false, true);
  992. var initialContent = "\u0100ert & Ann";
  993. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  994. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  995. {
  996. client.Connect();
  997. var remoteFile = GenerateUniqueRemoteFileName();
  998. if (client.Exists(remoteFile))
  999. {
  1000. client.DeleteFile(remoteFile);
  1001. }
  1002. try
  1003. {
  1004. using (client.CreateText(remoteFile))
  1005. {
  1006. }
  1007. // verify that empty file was created
  1008. Assert.IsTrue(client.Exists(remoteFile));
  1009. var file = client.GetAttributes(remoteFile);
  1010. Assert.AreEqual(0, file.Size);
  1011. client.DeleteFile(remoteFile);
  1012. using (var sw = client.CreateText(remoteFile))
  1013. {
  1014. sw.Write(initialContent);
  1015. }
  1016. // verify that content is written to file
  1017. var text = client.ReadAllText(remoteFile);
  1018. Assert.AreEqual(initialContent, text);
  1019. using (var fs = client.OpenRead(remoteFile))
  1020. {
  1021. var actualBytes = new byte[fs.Length];
  1022. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1023. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1024. }
  1025. }
  1026. finally
  1027. {
  1028. if (client.Exists(remoteFile))
  1029. {
  1030. client.DeleteFile(remoteFile);
  1031. }
  1032. }
  1033. }
  1034. }
  1035. [TestMethod]
  1036. public void Sftp_CreateText_Encoding_ExistingFile()
  1037. {
  1038. var encoding = GetRandomEncoding();
  1039. var initialContent = "\u0100ert & Ann";
  1040. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1041. var newContent = "\u0116ver";
  1042. var expectedContent = "\u0116ver" + " & Ann";
  1043. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  1044. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1045. {
  1046. client.Connect();
  1047. var remoteFile = GenerateUniqueRemoteFileName();
  1048. if (client.Exists(remoteFile))
  1049. {
  1050. client.DeleteFile(remoteFile);
  1051. }
  1052. try
  1053. {
  1054. client.WriteAllText(remoteFile, initialContent, encoding);
  1055. using (client.CreateText(remoteFile))
  1056. {
  1057. }
  1058. // verify that original content is left untouched
  1059. using (var fs = client.OpenRead(remoteFile))
  1060. {
  1061. var actualBytes = new byte[fs.Length];
  1062. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1063. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1064. }
  1065. // write content that is less bytes than original content
  1066. using (var sw = client.CreateText(remoteFile, encoding))
  1067. {
  1068. sw.Write(newContent);
  1069. }
  1070. // verify that original content is only partially overwritten
  1071. var text = client.ReadAllText(remoteFile, encoding);
  1072. Assert.AreEqual(expectedContent, text);
  1073. using (var fs = client.OpenRead(remoteFile))
  1074. {
  1075. var actualBytes = new byte[fs.Length];
  1076. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1077. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  1078. }
  1079. }
  1080. finally
  1081. {
  1082. if (client.Exists(remoteFile))
  1083. {
  1084. client.DeleteFile(remoteFile);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. [TestMethod]
  1090. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1091. {
  1092. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1093. var encoding = GetRandomEncoding();
  1094. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1095. {
  1096. client.Connect();
  1097. if (client.Exists(remoteFile))
  1098. {
  1099. client.DeleteFile(remoteFile);
  1100. }
  1101. StreamWriter sw = null;
  1102. try
  1103. {
  1104. sw = client.CreateText(remoteFile, encoding);
  1105. Assert.Fail();
  1106. }
  1107. catch (SftpPathNotFoundException ex)
  1108. {
  1109. Assert.IsNull(ex.InnerException);
  1110. Assert.AreEqual("No such file", ex.Message);
  1111. }
  1112. finally
  1113. {
  1114. sw?.Dispose();
  1115. if (client.Exists(remoteFile))
  1116. {
  1117. client.DeleteFile(remoteFile);
  1118. }
  1119. }
  1120. }
  1121. }
  1122. [TestMethod]
  1123. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1124. {
  1125. var encoding = GetRandomEncoding();
  1126. var initialContent = "\u0100ert & Ann";
  1127. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1128. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1129. {
  1130. client.Connect();
  1131. var remoteFile = GenerateUniqueRemoteFileName();
  1132. if (client.Exists(remoteFile))
  1133. {
  1134. client.DeleteFile(remoteFile);
  1135. }
  1136. try
  1137. {
  1138. using (client.CreateText(remoteFile, encoding))
  1139. {
  1140. }
  1141. // verify that file containing only preamble was created
  1142. Assert.IsTrue(client.Exists(remoteFile));
  1143. var file = client.GetAttributes(remoteFile);
  1144. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1145. client.DeleteFile(remoteFile);
  1146. using (var sw = client.CreateText(remoteFile, encoding))
  1147. {
  1148. sw.Write(initialContent);
  1149. }
  1150. // verify that content is written to file
  1151. var text = client.ReadAllText(remoteFile, encoding);
  1152. Assert.AreEqual(initialContent, text);
  1153. using (var fs = client.OpenRead(remoteFile))
  1154. {
  1155. var actualBytes = new byte[fs.Length];
  1156. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1157. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1158. }
  1159. }
  1160. finally
  1161. {
  1162. if (client.Exists(remoteFile))
  1163. {
  1164. client.DeleteFile(remoteFile);
  1165. }
  1166. }
  1167. }
  1168. }
  1169. [TestMethod]
  1170. public void Sftp_DownloadFile_FileDoesNotExist()
  1171. {
  1172. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1173. {
  1174. client.Connect();
  1175. var remoteFile = GenerateUniqueRemoteFileName();
  1176. if (client.Exists(remoteFile))
  1177. {
  1178. client.DeleteFile(remoteFile);
  1179. }
  1180. using (var ms = new MemoryStream())
  1181. {
  1182. try
  1183. {
  1184. client.DownloadFile(remoteFile, ms);
  1185. Assert.Fail();
  1186. }
  1187. catch (SftpPathNotFoundException ex)
  1188. {
  1189. Assert.IsNull(ex.InnerException);
  1190. Assert.AreEqual("No such file", ex.Message);
  1191. // ensure file was not created by us
  1192. Assert.IsFalse(client.Exists(remoteFile));
  1193. }
  1194. finally
  1195. {
  1196. if (client.Exists(remoteFile))
  1197. {
  1198. client.DeleteFile(remoteFile);
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. [TestMethod]
  1205. public void Sftp_ReadAllBytes_ExistingFile()
  1206. {
  1207. var encoding = GetRandomEncoding();
  1208. var content = "\u0100ert & Ann";
  1209. var contentBytes = GetBytesWithPreamble(content, encoding);
  1210. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1211. {
  1212. client.Connect();
  1213. var remoteFile = GenerateUniqueRemoteFileName();
  1214. if (client.Exists(remoteFile))
  1215. {
  1216. client.DeleteFile(remoteFile);
  1217. }
  1218. try
  1219. {
  1220. client.WriteAllText(remoteFile, content, encoding);
  1221. var actualBytes = client.ReadAllBytes(remoteFile);
  1222. Assert.IsTrue(contentBytes.IsEqualTo(actualBytes));
  1223. }
  1224. finally
  1225. {
  1226. if (client.Exists(remoteFile))
  1227. {
  1228. client.DeleteFile(remoteFile);
  1229. }
  1230. }
  1231. }
  1232. }
  1233. [TestMethod]
  1234. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1235. {
  1236. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1237. {
  1238. client.Connect();
  1239. var remoteFile = GenerateUniqueRemoteFileName();
  1240. if (client.Exists(remoteFile))
  1241. {
  1242. client.DeleteFile(remoteFile);
  1243. }
  1244. try
  1245. {
  1246. client.ReadAllBytes(remoteFile);
  1247. Assert.Fail();
  1248. }
  1249. catch (SftpPathNotFoundException ex)
  1250. {
  1251. Assert.IsNull(ex.InnerException);
  1252. Assert.AreEqual("No such file", ex.Message);
  1253. // ensure file was not created by us
  1254. Assert.IsFalse(client.Exists(remoteFile));
  1255. }
  1256. finally
  1257. {
  1258. if (client.Exists(remoteFile))
  1259. {
  1260. client.DeleteFile(remoteFile);
  1261. }
  1262. }
  1263. }
  1264. }
  1265. [TestMethod]
  1266. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1267. {
  1268. var encoding = new UTF8Encoding(false, true);
  1269. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1270. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1271. encoding);
  1272. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1273. {
  1274. client.Connect();
  1275. var remoteFile = GenerateUniqueRemoteFileName();
  1276. if (client.Exists(remoteFile))
  1277. {
  1278. client.DeleteFile(remoteFile);
  1279. }
  1280. try
  1281. {
  1282. using (var sw = client.AppendText(remoteFile))
  1283. {
  1284. for (var i = 0; i < lines.Length; i++)
  1285. {
  1286. sw.WriteLine(lines[i]);
  1287. }
  1288. }
  1289. var actualLines = client.ReadAllLines(remoteFile);
  1290. Assert.IsNotNull(actualLines);
  1291. Assert.AreEqual(lines.Length, actualLines.Length);
  1292. for (var i = 0; i < lines.Length; i++)
  1293. {
  1294. Assert.AreEqual(lines[i], actualLines[i]);
  1295. }
  1296. using (var fs = client.OpenRead(remoteFile))
  1297. {
  1298. var actualBytes = new byte[fs.Length];
  1299. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1300. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1301. }
  1302. }
  1303. finally
  1304. {
  1305. if (client.Exists(remoteFile))
  1306. {
  1307. client.DeleteFile(remoteFile);
  1308. }
  1309. }
  1310. }
  1311. }
  1312. [TestMethod]
  1313. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1314. {
  1315. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1316. {
  1317. client.Connect();
  1318. var remoteFile = GenerateUniqueRemoteFileName();
  1319. if (client.Exists(remoteFile))
  1320. {
  1321. client.DeleteFile(remoteFile);
  1322. }
  1323. try
  1324. {
  1325. client.ReadAllLines(remoteFile);
  1326. Assert.Fail();
  1327. }
  1328. catch (SftpPathNotFoundException ex)
  1329. {
  1330. Assert.IsNull(ex.InnerException);
  1331. Assert.AreEqual("No such file", ex.Message);
  1332. // ensure file was not created by us
  1333. Assert.IsFalse(client.Exists(remoteFile));
  1334. }
  1335. finally
  1336. {
  1337. if (client.Exists(remoteFile))
  1338. {
  1339. client.DeleteFile(remoteFile);
  1340. }
  1341. }
  1342. }
  1343. }
  1344. [TestMethod]
  1345. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1346. {
  1347. var encoding = GetRandomEncoding();
  1348. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1349. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1350. encoding);
  1351. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1352. {
  1353. client.Connect();
  1354. var remoteFile = GenerateUniqueRemoteFileName();
  1355. if (client.Exists(remoteFile))
  1356. {
  1357. client.DeleteFile(remoteFile);
  1358. }
  1359. try
  1360. {
  1361. using (var sw = client.AppendText(remoteFile, encoding))
  1362. {
  1363. for (var i = 0; i < lines.Length; i++)
  1364. {
  1365. sw.WriteLine(lines[i]);
  1366. }
  1367. }
  1368. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1369. Assert.IsNotNull(actualLines);
  1370. Assert.AreEqual(lines.Length, actualLines.Length);
  1371. for (var i = 0; i < lines.Length; i++)
  1372. {
  1373. Assert.AreEqual(lines[i], actualLines[i]);
  1374. }
  1375. using (var fs = client.OpenRead(remoteFile))
  1376. {
  1377. var actualBytes = new byte[fs.Length];
  1378. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1379. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1380. }
  1381. }
  1382. finally
  1383. {
  1384. if (client.Exists(remoteFile))
  1385. {
  1386. client.DeleteFile(remoteFile);
  1387. }
  1388. }
  1389. }
  1390. }
  1391. [TestMethod]
  1392. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1393. {
  1394. var encoding = GetRandomEncoding();
  1395. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1396. {
  1397. client.Connect();
  1398. var remoteFile = GenerateUniqueRemoteFileName();
  1399. if (client.Exists(remoteFile))
  1400. {
  1401. client.DeleteFile(remoteFile);
  1402. }
  1403. try
  1404. {
  1405. client.ReadAllLines(remoteFile, encoding);
  1406. Assert.Fail();
  1407. }
  1408. catch (SftpPathNotFoundException ex)
  1409. {
  1410. Assert.IsNull(ex.InnerException);
  1411. Assert.AreEqual("No such file", ex.Message);
  1412. // ensure file was not created by us
  1413. Assert.IsFalse(client.Exists(remoteFile));
  1414. }
  1415. finally
  1416. {
  1417. if (client.Exists(remoteFile))
  1418. {
  1419. client.DeleteFile(remoteFile);
  1420. }
  1421. }
  1422. }
  1423. }
  1424. [TestMethod]
  1425. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1426. {
  1427. var encoding = new UTF8Encoding(false, true);
  1428. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1429. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1430. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1431. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1432. {
  1433. client.Connect();
  1434. var remoteFile = GenerateUniqueRemoteFileName();
  1435. if (client.Exists(remoteFile))
  1436. {
  1437. client.DeleteFile(remoteFile);
  1438. }
  1439. try
  1440. {
  1441. using (var sw = client.AppendText(remoteFile))
  1442. {
  1443. for (var i = 0; i < lines.Length; i++)
  1444. {
  1445. sw.WriteLine(lines[i]);
  1446. }
  1447. }
  1448. var actualText = client.ReadAllText(remoteFile);
  1449. Assert.AreEqual(expectedText, actualText);
  1450. using (var fs = client.OpenRead(remoteFile))
  1451. {
  1452. var actualBytes = new byte[fs.Length];
  1453. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1454. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1455. }
  1456. }
  1457. finally
  1458. {
  1459. if (client.Exists(remoteFile))
  1460. {
  1461. client.DeleteFile(remoteFile);
  1462. }
  1463. }
  1464. }
  1465. }
  1466. [TestMethod]
  1467. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1468. {
  1469. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1470. {
  1471. client.Connect();
  1472. var remoteFile = GenerateUniqueRemoteFileName();
  1473. if (client.Exists(remoteFile))
  1474. {
  1475. client.DeleteFile(remoteFile);
  1476. }
  1477. try
  1478. {
  1479. client.ReadAllText(remoteFile);
  1480. Assert.Fail();
  1481. }
  1482. catch (SftpPathNotFoundException ex)
  1483. {
  1484. Assert.IsNull(ex.InnerException);
  1485. Assert.AreEqual("No such file", ex.Message);
  1486. // ensure file was not created by us
  1487. Assert.IsFalse(client.Exists(remoteFile));
  1488. }
  1489. finally
  1490. {
  1491. if (client.Exists(remoteFile))
  1492. {
  1493. client.DeleteFile(remoteFile);
  1494. }
  1495. }
  1496. }
  1497. }
  1498. [TestMethod]
  1499. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1500. {
  1501. var encoding = GetRandomEncoding();
  1502. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1503. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1504. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1505. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1506. {
  1507. client.Connect();
  1508. var remoteFile = GenerateUniqueRemoteFileName();
  1509. if (client.Exists(remoteFile))
  1510. {
  1511. client.DeleteFile(remoteFile);
  1512. }
  1513. try
  1514. {
  1515. using (var sw = client.AppendText(remoteFile, encoding))
  1516. {
  1517. for (var i = 0; i < lines.Length; i++)
  1518. {
  1519. sw.WriteLine(lines[i]);
  1520. }
  1521. }
  1522. var actualText = client.ReadAllText(remoteFile, encoding);
  1523. Assert.AreEqual(expectedText, actualText);
  1524. using (var fs = client.OpenRead(remoteFile))
  1525. {
  1526. var actualBytes = new byte[fs.Length];
  1527. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1528. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1529. }
  1530. }
  1531. finally
  1532. {
  1533. if (client.Exists(remoteFile))
  1534. {
  1535. client.DeleteFile(remoteFile);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. [TestMethod]
  1541. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1542. {
  1543. var encoding = GetRandomEncoding();
  1544. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1545. {
  1546. client.Connect();
  1547. var remoteFile = GenerateUniqueRemoteFileName();
  1548. if (client.Exists(remoteFile))
  1549. {
  1550. client.DeleteFile(remoteFile);
  1551. }
  1552. try
  1553. {
  1554. client.ReadAllText(remoteFile, encoding);
  1555. Assert.Fail();
  1556. }
  1557. catch (SftpPathNotFoundException ex)
  1558. {
  1559. Assert.IsNull(ex.InnerException);
  1560. Assert.AreEqual("No such file", ex.Message);
  1561. // ensure file was not created by us
  1562. Assert.IsFalse(client.Exists(remoteFile));
  1563. }
  1564. finally
  1565. {
  1566. if (client.Exists(remoteFile))
  1567. {
  1568. client.DeleteFile(remoteFile);
  1569. }
  1570. }
  1571. }
  1572. }
  1573. [TestMethod]
  1574. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1575. {
  1576. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1577. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1578. {
  1579. client.Connect();
  1580. var remoteFile = GenerateUniqueRemoteFileName();
  1581. if (client.Exists(remoteFile))
  1582. {
  1583. client.DeleteFile(remoteFile);
  1584. }
  1585. try
  1586. {
  1587. using (var sw = client.AppendText(remoteFile))
  1588. {
  1589. for (var i = 0; i < lines.Length; i++)
  1590. {
  1591. sw.WriteLine(lines[i]);
  1592. }
  1593. }
  1594. var actualLines = client.ReadLines(remoteFile);
  1595. Assert.IsNotNull(actualLines);
  1596. var actualLinesEnum = actualLines.GetEnumerator();
  1597. for (var i = 0; i < lines.Length; i++)
  1598. {
  1599. Assert.IsTrue(actualLinesEnum.MoveNext());
  1600. var actualLine = actualLinesEnum.Current;
  1601. Assert.AreEqual(lines[i], actualLine);
  1602. }
  1603. Assert.IsFalse(actualLinesEnum.MoveNext());
  1604. }
  1605. finally
  1606. {
  1607. if (client.Exists(remoteFile))
  1608. {
  1609. client.DeleteFile(remoteFile);
  1610. }
  1611. }
  1612. }
  1613. }
  1614. [TestMethod]
  1615. public void Sftp_ReadLines_NoEncoding_FileDoesNotExist()
  1616. {
  1617. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1618. {
  1619. client.Connect();
  1620. var remoteFile = GenerateUniqueRemoteFileName();
  1621. if (client.Exists(remoteFile))
  1622. {
  1623. client.DeleteFile(remoteFile);
  1624. }
  1625. try
  1626. {
  1627. client.ReadLines(remoteFile);
  1628. Assert.Fail();
  1629. }
  1630. catch (SftpPathNotFoundException ex)
  1631. {
  1632. Assert.IsNull(ex.InnerException);
  1633. Assert.AreEqual("No such file", ex.Message);
  1634. // ensure file was not created by us
  1635. Assert.IsFalse(client.Exists(remoteFile));
  1636. }
  1637. finally
  1638. {
  1639. if (client.Exists(remoteFile))
  1640. {
  1641. client.DeleteFile(remoteFile);
  1642. }
  1643. }
  1644. }
  1645. }
  1646. [TestMethod]
  1647. public void Sftp_ReadLines_Encoding_ExistingFile()
  1648. {
  1649. var encoding = GetRandomEncoding();
  1650. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1651. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1652. {
  1653. client.Connect();
  1654. var remoteFile = GenerateUniqueRemoteFileName();
  1655. if (client.Exists(remoteFile))
  1656. {
  1657. client.DeleteFile(remoteFile);
  1658. }
  1659. try
  1660. {
  1661. using (var sw = client.AppendText(remoteFile, encoding))
  1662. {
  1663. for (var i = 0; i < lines.Length; i++)
  1664. {
  1665. sw.WriteLine(lines[i]);
  1666. }
  1667. }
  1668. var actualLines = client.ReadLines(remoteFile, encoding);
  1669. Assert.IsNotNull(actualLines);
  1670. using (var actualLinesEnum = actualLines.GetEnumerator())
  1671. {
  1672. for (var i = 0; i < lines.Length; i++)
  1673. {
  1674. Assert.IsTrue(actualLinesEnum.MoveNext());
  1675. var actualLine = actualLinesEnum.Current;
  1676. Assert.AreEqual(lines[i], actualLine);
  1677. }
  1678. Assert.IsFalse(actualLinesEnum.MoveNext());
  1679. }
  1680. }
  1681. finally
  1682. {
  1683. if (client.Exists(remoteFile))
  1684. {
  1685. client.DeleteFile(remoteFile);
  1686. }
  1687. }
  1688. }
  1689. }
  1690. [TestMethod]
  1691. public void Sftp_ReadLines_Encoding_FileDoesNotExist()
  1692. {
  1693. var encoding = GetRandomEncoding();
  1694. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1695. {
  1696. client.Connect();
  1697. var remoteFile = GenerateUniqueRemoteFileName();
  1698. if (client.Exists(remoteFile))
  1699. {
  1700. client.DeleteFile(remoteFile);
  1701. }
  1702. try
  1703. {
  1704. client.ReadLines(remoteFile, encoding);
  1705. Assert.Fail();
  1706. }
  1707. catch (SftpPathNotFoundException ex)
  1708. {
  1709. Assert.IsNull(ex.InnerException);
  1710. Assert.AreEqual("No such file", ex.Message);
  1711. // ensure file was not created by us
  1712. Assert.IsFalse(client.Exists(remoteFile));
  1713. }
  1714. finally
  1715. {
  1716. if (client.Exists(remoteFile))
  1717. {
  1718. client.DeleteFile(remoteFile);
  1719. }
  1720. }
  1721. }
  1722. }
  1723. [TestMethod]
  1724. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1725. {
  1726. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1727. var content = GenerateRandom(size: 5);
  1728. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1729. {
  1730. client.Connect();
  1731. if (client.Exists(remoteFile))
  1732. {
  1733. client.DeleteFile(remoteFile);
  1734. }
  1735. try
  1736. {
  1737. client.WriteAllBytes(remoteFile, content);
  1738. Assert.Fail();
  1739. }
  1740. catch (SftpPathNotFoundException ex)
  1741. {
  1742. Assert.IsNull(ex.InnerException);
  1743. Assert.AreEqual("No such file", ex.Message);
  1744. }
  1745. finally
  1746. {
  1747. if (client.Exists(remoteFile))
  1748. {
  1749. client.DeleteFile(remoteFile);
  1750. }
  1751. }
  1752. }
  1753. }
  1754. [TestMethod]
  1755. public void Sftp_WriteAllBytes_ExistingFile()
  1756. {
  1757. var initialContent = GenerateRandom(size: 13);
  1758. var newContent1 = GenerateRandom(size: 5);
  1759. var expectedContent1 = new ArrayBuilder<byte>().Add(newContent1)
  1760. .Add(initialContent, newContent1.Length, initialContent.Length - newContent1.Length)
  1761. .Build();
  1762. var newContent2 = GenerateRandom(size: 50000);
  1763. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1764. {
  1765. client.Connect();
  1766. var remoteFile = GenerateUniqueRemoteFileName();
  1767. if (client.Exists(remoteFile))
  1768. {
  1769. client.DeleteFile(remoteFile);
  1770. }
  1771. try
  1772. {
  1773. using (var fs = client.Create(remoteFile))
  1774. {
  1775. fs.Write(initialContent, offset: 0, initialContent.Length);
  1776. }
  1777. #region Write less bytes than the current content, overwriting part of that content
  1778. client.WriteAllBytes(remoteFile, newContent1);
  1779. var actualContent1 = client.ReadAllBytes(remoteFile);
  1780. Assert.IsTrue(expectedContent1.IsEqualTo(actualContent1));
  1781. #endregion Write less bytes than the initial content, overwriting part of that content
  1782. #region Write more bytes than the current content, overwriting and appending to that content
  1783. client.WriteAllBytes(remoteFile, newContent2);
  1784. var actualContent2 = client.ReadAllBytes(remoteFile);
  1785. Assert.IsTrue(newContent2.IsEqualTo(actualContent2));
  1786. #endregion Write less bytes than the initial content, overwriting part of that content
  1787. }
  1788. finally
  1789. {
  1790. if (client.Exists(remoteFile))
  1791. {
  1792. client.DeleteFile(remoteFile);
  1793. }
  1794. }
  1795. }
  1796. }
  1797. [TestMethod]
  1798. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1799. {
  1800. var content = GenerateRandom(size: 13);
  1801. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1802. {
  1803. client.Connect();
  1804. var remoteFile = GenerateUniqueRemoteFileName();
  1805. if (client.Exists(remoteFile))
  1806. {
  1807. client.DeleteFile(remoteFile);
  1808. }
  1809. try
  1810. {
  1811. client.WriteAllBytes(remoteFile, content);
  1812. using (var fs = client.OpenRead(remoteFile))
  1813. {
  1814. var actualBytes = new byte[fs.Length];
  1815. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1816. Assert.IsTrue(content.IsEqualTo(actualBytes));
  1817. }
  1818. }
  1819. finally
  1820. {
  1821. if (client.Exists(remoteFile))
  1822. {
  1823. client.DeleteFile(remoteFile);
  1824. }
  1825. }
  1826. }
  1827. }
  1828. [TestMethod]
  1829. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1830. {
  1831. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1832. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1833. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1834. {
  1835. client.Connect();
  1836. if (client.Exists(remoteFile))
  1837. {
  1838. client.DeleteFile(remoteFile);
  1839. }
  1840. try
  1841. {
  1842. client.WriteAllLines(remoteFile, linesToWrite);
  1843. Assert.Fail();
  1844. }
  1845. catch (SftpPathNotFoundException ex)
  1846. {
  1847. Assert.IsNull(ex.InnerException);
  1848. Assert.AreEqual("No such file", ex.Message);
  1849. }
  1850. finally
  1851. {
  1852. if (client.Exists(remoteFile))
  1853. {
  1854. client.DeleteFile(remoteFile);
  1855. }
  1856. }
  1857. }
  1858. }
  1859. [TestMethod]
  1860. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1861. {
  1862. var encoding = new UTF8Encoding(false, true);
  1863. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1864. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1865. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1866. var linesToWrite1Bytes =
  1867. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1868. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1869. .Add(initialContentBytes,
  1870. linesToWrite1Bytes.Length,
  1871. initialContentBytes.Length - linesToWrite1Bytes.Length)
  1872. .Build();
  1873. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1874. var linesToWrite2Bytes =
  1875. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1876. var expectedBytes2 = linesToWrite2Bytes;
  1877. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1878. {
  1879. client.Connect();
  1880. var remoteFile = GenerateUniqueRemoteFileName();
  1881. if (client.Exists(remoteFile))
  1882. {
  1883. client.DeleteFile(remoteFile);
  1884. }
  1885. try
  1886. {
  1887. // create initial content
  1888. client.WriteAllText(remoteFile, initialContent);
  1889. #region Write less bytes than the current content, overwriting part of that content
  1890. client.WriteAllLines(remoteFile, linesToWrite1);
  1891. using (var fs = client.OpenRead(remoteFile))
  1892. {
  1893. var actualBytes = new byte[fs.Length];
  1894. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1895. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  1896. }
  1897. #endregion Write less bytes than the current content, overwriting part of that content
  1898. #region Write more bytes than the current content, overwriting and appending to that content
  1899. client.WriteAllLines(remoteFile, linesToWrite2);
  1900. using (var fs = client.OpenRead(remoteFile))
  1901. {
  1902. var actualBytes = new byte[fs.Length];
  1903. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1904. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  1905. }
  1906. #endregion Write more bytes than the current content, overwriting and appending to that content
  1907. }
  1908. finally
  1909. {
  1910. if (client.Exists(remoteFile))
  1911. {
  1912. client.DeleteFile(remoteFile);
  1913. }
  1914. }
  1915. }
  1916. }
  1917. [TestMethod]
  1918. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1919. {
  1920. var encoding = new UTF8Encoding(false, true);
  1921. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1922. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1923. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1924. {
  1925. client.Connect();
  1926. var remoteFile = GenerateUniqueRemoteFileName();
  1927. if (client.Exists(remoteFile))
  1928. {
  1929. client.DeleteFile(remoteFile);
  1930. }
  1931. try
  1932. {
  1933. client.WriteAllLines(remoteFile, linesToWrite);
  1934. using (var fs = client.OpenRead(remoteFile))
  1935. {
  1936. var actualBytes = new byte[fs.Length];
  1937. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1938. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  1939. }
  1940. }
  1941. finally
  1942. {
  1943. if (client.Exists(remoteFile))
  1944. {
  1945. client.DeleteFile(remoteFile);
  1946. }
  1947. }
  1948. }
  1949. }
  1950. [TestMethod]
  1951. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1952. {
  1953. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1954. var encoding = GetRandomEncoding();
  1955. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1956. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1957. {
  1958. client.Connect();
  1959. if (client.Exists(remoteFile))
  1960. {
  1961. client.DeleteFile(remoteFile);
  1962. }
  1963. try
  1964. {
  1965. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1966. Assert.Fail();
  1967. }
  1968. catch (SftpPathNotFoundException ex)
  1969. {
  1970. Assert.IsNull(ex.InnerException);
  1971. Assert.AreEqual("No such file", ex.Message);
  1972. }
  1973. finally
  1974. {
  1975. if (client.Exists(remoteFile))
  1976. {
  1977. client.DeleteFile(remoteFile);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. [TestMethod]
  1983. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1984. {
  1985. var encoding = GetRandomEncoding();
  1986. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1987. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1988. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1989. var linesToWrite1Bytes =
  1990. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1991. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1992. .Add(initialContentBytes,
  1993. linesToWrite1Bytes.Length,
  1994. initialContentBytes.Length - linesToWrite1Bytes.Length)
  1995. .Build();
  1996. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1997. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1998. var expectedBytes2 = linesToWrite2Bytes;
  1999. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2000. {
  2001. client.Connect();
  2002. var remoteFile = GenerateUniqueRemoteFileName();
  2003. if (client.Exists(remoteFile))
  2004. {
  2005. client.DeleteFile(remoteFile);
  2006. }
  2007. try
  2008. {
  2009. // create initial content
  2010. client.WriteAllText(remoteFile, initialContent, encoding);
  2011. #region Write less bytes than the current content, overwriting part of that content
  2012. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2013. using (var fs = client.OpenRead(remoteFile))
  2014. {
  2015. var actualBytes = new byte[fs.Length];
  2016. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2017. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2018. }
  2019. #endregion Write less bytes than the current content, overwriting part of that content
  2020. #region Write more bytes than the current content, overwriting and appending to that content
  2021. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2022. using (var fs = client.OpenRead(remoteFile))
  2023. {
  2024. var actualBytes = new byte[fs.Length];
  2025. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2026. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2027. }
  2028. #endregion Write more bytes than the current content, overwriting and appending to that content
  2029. }
  2030. finally
  2031. {
  2032. if (client.Exists(remoteFile))
  2033. {
  2034. client.DeleteFile(remoteFile);
  2035. }
  2036. }
  2037. }
  2038. }
  2039. [TestMethod]
  2040. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  2041. {
  2042. var encoding = GetRandomEncoding();
  2043. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2044. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2045. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2046. {
  2047. client.Connect();
  2048. var remoteFile = GenerateUniqueRemoteFileName();
  2049. if (client.Exists(remoteFile))
  2050. {
  2051. client.DeleteFile(remoteFile);
  2052. }
  2053. try
  2054. {
  2055. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2056. using (var fs = client.OpenRead(remoteFile))
  2057. {
  2058. var actualBytes = new byte[fs.Length];
  2059. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2060. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2061. }
  2062. }
  2063. finally
  2064. {
  2065. if (client.Exists(remoteFile))
  2066. {
  2067. client.DeleteFile(remoteFile);
  2068. }
  2069. }
  2070. }
  2071. }
  2072. [TestMethod]
  2073. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  2074. {
  2075. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2076. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2077. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2078. {
  2079. client.Connect();
  2080. if (client.Exists(remoteFile))
  2081. {
  2082. client.DeleteFile(remoteFile);
  2083. }
  2084. try
  2085. {
  2086. client.WriteAllLines(remoteFile, linesToWrite);
  2087. Assert.Fail();
  2088. }
  2089. catch (SftpPathNotFoundException ex)
  2090. {
  2091. Assert.IsNull(ex.InnerException);
  2092. Assert.AreEqual("No such file", ex.Message);
  2093. }
  2094. finally
  2095. {
  2096. if (client.Exists(remoteFile))
  2097. {
  2098. client.DeleteFile(remoteFile);
  2099. }
  2100. }
  2101. }
  2102. }
  2103. [TestMethod]
  2104. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  2105. {
  2106. var encoding = new UTF8Encoding(false, true);
  2107. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2108. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2109. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2110. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2111. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2112. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2113. .Build();
  2114. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2115. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2116. var expectedBytes2 = linesToWrite2Bytes;
  2117. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2118. {
  2119. client.Connect();
  2120. var remoteFile = GenerateUniqueRemoteFileName();
  2121. if (client.Exists(remoteFile))
  2122. {
  2123. client.DeleteFile(remoteFile);
  2124. }
  2125. try
  2126. {
  2127. // create initial content
  2128. client.WriteAllText(remoteFile, initialContent);
  2129. #region Write less bytes than the current content, overwriting part of that content
  2130. client.WriteAllLines(remoteFile, linesToWrite1);
  2131. using (var fs = client.OpenRead(remoteFile))
  2132. {
  2133. var actualBytes = new byte[fs.Length];
  2134. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2135. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2136. }
  2137. #endregion Write less bytes than the current content, overwriting part of that content
  2138. #region Write more bytes than the current content, overwriting and appending to that content
  2139. client.WriteAllLines(remoteFile, linesToWrite2);
  2140. using (var fs = client.OpenRead(remoteFile))
  2141. {
  2142. var actualBytes = new byte[fs.Length];
  2143. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2144. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2145. }
  2146. #endregion Write more bytes than the current content, overwriting and appending to that content
  2147. }
  2148. finally
  2149. {
  2150. if (client.Exists(remoteFile))
  2151. {
  2152. client.DeleteFile(remoteFile);
  2153. }
  2154. }
  2155. }
  2156. }
  2157. [TestMethod]
  2158. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  2159. {
  2160. var encoding = new UTF8Encoding(false, true);
  2161. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2162. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2163. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2164. {
  2165. client.Connect();
  2166. var remoteFile = GenerateUniqueRemoteFileName();
  2167. if (client.Exists(remoteFile))
  2168. {
  2169. client.DeleteFile(remoteFile);
  2170. }
  2171. try
  2172. {
  2173. client.WriteAllLines(remoteFile, linesToWrite);
  2174. using (var fs = client.OpenRead(remoteFile))
  2175. {
  2176. var actualBytes = new byte[fs.Length];
  2177. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2178. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2179. }
  2180. }
  2181. finally
  2182. {
  2183. if (client.Exists(remoteFile))
  2184. {
  2185. client.DeleteFile(remoteFile);
  2186. }
  2187. }
  2188. }
  2189. }
  2190. [TestMethod]
  2191. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  2192. {
  2193. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2194. var encoding = GetRandomEncoding();
  2195. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2196. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2197. {
  2198. client.Connect();
  2199. if (client.Exists(remoteFile))
  2200. {
  2201. client.DeleteFile(remoteFile);
  2202. }
  2203. try
  2204. {
  2205. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2206. Assert.Fail();
  2207. }
  2208. catch (SftpPathNotFoundException ex)
  2209. {
  2210. Assert.IsNull(ex.InnerException);
  2211. Assert.AreEqual("No such file", ex.Message);
  2212. }
  2213. finally
  2214. {
  2215. if (client.Exists(remoteFile))
  2216. {
  2217. client.DeleteFile(remoteFile);
  2218. }
  2219. }
  2220. }
  2221. }
  2222. [TestMethod]
  2223. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2224. {
  2225. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2226. var encoding = GetRandomEncoding();
  2227. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2228. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2229. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2230. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2231. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2232. .Build();
  2233. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2234. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2235. var expectedBytes2 = linesToWrite2Bytes;
  2236. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2237. {
  2238. client.Connect();
  2239. var remoteFile = GenerateUniqueRemoteFileName();
  2240. if (client.Exists(remoteFile))
  2241. {
  2242. client.DeleteFile(remoteFile);
  2243. }
  2244. try
  2245. {
  2246. // create initial content
  2247. client.WriteAllText(remoteFile, initialContent, encoding);
  2248. #region Write less bytes than the current content, overwriting part of that content
  2249. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2250. using (var fs = client.OpenRead(remoteFile))
  2251. {
  2252. var actualBytes = new byte[fs.Length];
  2253. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2254. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2255. }
  2256. #endregion Write less bytes than the current content, overwriting part of that content
  2257. #region Write more bytes than the current content, overwriting and appending to that content
  2258. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2259. using (var fs = client.OpenRead(remoteFile))
  2260. {
  2261. var actualBytes = new byte[fs.Length];
  2262. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2263. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2264. }
  2265. #endregion Write more bytes than the current content, overwriting and appending to that content
  2266. }
  2267. finally
  2268. {
  2269. if (client.Exists(remoteFile))
  2270. {
  2271. client.DeleteFile(remoteFile);
  2272. }
  2273. }
  2274. }
  2275. }
  2276. [TestMethod]
  2277. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2278. {
  2279. var encoding = GetRandomEncoding();
  2280. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2281. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2282. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2283. {
  2284. client.Connect();
  2285. var remoteFile = GenerateUniqueRemoteFileName();
  2286. if (client.Exists(remoteFile))
  2287. {
  2288. client.DeleteFile(remoteFile);
  2289. }
  2290. try
  2291. {
  2292. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2293. using (var fs = client.OpenRead(remoteFile))
  2294. {
  2295. var actualBytes = new byte[fs.Length];
  2296. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2297. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2298. }
  2299. }
  2300. finally
  2301. {
  2302. if (client.Exists(remoteFile))
  2303. {
  2304. client.DeleteFile(remoteFile);
  2305. }
  2306. }
  2307. }
  2308. }
  2309. [TestMethod]
  2310. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2311. {
  2312. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2313. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2314. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2315. {
  2316. client.Connect();
  2317. if (client.Exists(remoteFile))
  2318. {
  2319. client.DeleteFile(remoteFile);
  2320. }
  2321. try
  2322. {
  2323. client.WriteAllText(remoteFile, initialContent);
  2324. Assert.Fail();
  2325. }
  2326. catch (SftpPathNotFoundException ex)
  2327. {
  2328. Assert.IsNull(ex.InnerException);
  2329. Assert.AreEqual("No such file", ex.Message);
  2330. }
  2331. finally
  2332. {
  2333. if (client.Exists(remoteFile))
  2334. {
  2335. client.DeleteFile(remoteFile);
  2336. }
  2337. }
  2338. }
  2339. }
  2340. [TestMethod]
  2341. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2342. {
  2343. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2344. const string newContent1 = "For\u0116ver & Ever";
  2345. var encoding = new UTF8Encoding(false, true);
  2346. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2347. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2348. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2349. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2350. .Build();
  2351. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2352. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2353. var expectedBytes2 = newContent2Bytes;
  2354. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2355. {
  2356. client.Connect();
  2357. var remoteFile = GenerateUniqueRemoteFileName();
  2358. if (client.Exists(remoteFile))
  2359. {
  2360. client.DeleteFile(remoteFile);
  2361. }
  2362. try
  2363. {
  2364. client.WriteAllText(remoteFile, initialContent);
  2365. #region Write less bytes than the current content, overwriting part of that content
  2366. client.WriteAllText(remoteFile, newContent1);
  2367. using (var fs = client.OpenRead(remoteFile))
  2368. {
  2369. var actualBytes = new byte[fs.Length];
  2370. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2371. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2372. }
  2373. #endregion Write less bytes than the current content, overwriting part of that content
  2374. #region Write more bytes than the current content, overwriting and appending to that content
  2375. client.WriteAllText(remoteFile, newContent2);
  2376. using (var fs = client.OpenRead(remoteFile))
  2377. {
  2378. var actualBytes = new byte[fs.Length];
  2379. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2380. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2381. }
  2382. #endregion Write more bytes than the current content, overwriting and appending to that content
  2383. }
  2384. finally
  2385. {
  2386. if (client.Exists(remoteFile))
  2387. {
  2388. client.DeleteFile(remoteFile);
  2389. }
  2390. }
  2391. }
  2392. }
  2393. [TestMethod]
  2394. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2395. {
  2396. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2397. var encoding = new UTF8Encoding(false, true);
  2398. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2399. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2400. {
  2401. client.Connect();
  2402. var remoteFile = GenerateUniqueRemoteFileName();
  2403. if (client.Exists(remoteFile))
  2404. {
  2405. client.DeleteFile(remoteFile);
  2406. }
  2407. try
  2408. {
  2409. client.WriteAllText(remoteFile, initialContent);
  2410. using (var fs = client.OpenRead(remoteFile))
  2411. {
  2412. var actualBytes = new byte[fs.Length];
  2413. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2414. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2415. }
  2416. }
  2417. finally
  2418. {
  2419. if (client.Exists(remoteFile))
  2420. {
  2421. client.DeleteFile(remoteFile);
  2422. }
  2423. }
  2424. }
  2425. }
  2426. [TestMethod]
  2427. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2428. {
  2429. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2430. var encoding = GetRandomEncoding();
  2431. const string content = "For\u0116ver & Ever";
  2432. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2433. {
  2434. client.Connect();
  2435. if (client.Exists(remoteFile))
  2436. {
  2437. client.DeleteFile(remoteFile);
  2438. }
  2439. try
  2440. {
  2441. client.WriteAllText(remoteFile, content, encoding);
  2442. Assert.Fail();
  2443. }
  2444. catch (SftpPathNotFoundException ex)
  2445. {
  2446. Assert.IsNull(ex.InnerException);
  2447. Assert.AreEqual("No such file", ex.Message);
  2448. }
  2449. finally
  2450. {
  2451. if (client.Exists(remoteFile))
  2452. {
  2453. client.DeleteFile(remoteFile);
  2454. }
  2455. }
  2456. }
  2457. }
  2458. [TestMethod]
  2459. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2460. {
  2461. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2462. const string newContent1 = "For\u0116ver & Ever";
  2463. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2464. var encoding = GetRandomEncoding();
  2465. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2466. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2467. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2468. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2469. .Build();
  2470. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2471. var expectedBytes2 = newContent2Bytes;
  2472. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2473. {
  2474. client.Connect();
  2475. var remoteFile = GenerateUniqueRemoteFileName();
  2476. if (client.Exists(remoteFile))
  2477. {
  2478. client.DeleteFile(remoteFile);
  2479. }
  2480. try
  2481. {
  2482. client.WriteAllText(remoteFile, initialContent, encoding);
  2483. #region Write less bytes than the current content, overwriting part of that content
  2484. client.WriteAllText(remoteFile, newContent1, encoding);
  2485. using (var fs = client.OpenRead(remoteFile))
  2486. {
  2487. var actualBytes = new byte[fs.Length];
  2488. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2489. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2490. }
  2491. #endregion Write less bytes than the current content, overwriting part of that content
  2492. #region Write more bytes than the current content, overwriting and appending to that content
  2493. client.WriteAllText(remoteFile, newContent2, encoding);
  2494. using (var fs = client.OpenRead(remoteFile))
  2495. {
  2496. var actualBytes = new byte[fs.Length];
  2497. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2498. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2499. }
  2500. #endregion Write more bytes than the current content, overwriting and appending to that content
  2501. }
  2502. finally
  2503. {
  2504. if (client.Exists(remoteFile))
  2505. {
  2506. client.DeleteFile(remoteFile);
  2507. }
  2508. }
  2509. }
  2510. }
  2511. [TestMethod]
  2512. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2513. {
  2514. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2515. var encoding = GetRandomEncoding();
  2516. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2517. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2518. {
  2519. client.Connect();
  2520. var remoteFile = GenerateUniqueRemoteFileName();
  2521. if (client.Exists(remoteFile))
  2522. {
  2523. client.DeleteFile(remoteFile);
  2524. }
  2525. try
  2526. {
  2527. client.WriteAllText(remoteFile, initialContent, encoding);
  2528. using (var fs = client.OpenRead(remoteFile))
  2529. {
  2530. var actualBytes = new byte[fs.Length];
  2531. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2532. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2533. }
  2534. }
  2535. finally
  2536. {
  2537. if (client.Exists(remoteFile))
  2538. {
  2539. client.DeleteFile(remoteFile);
  2540. }
  2541. }
  2542. }
  2543. }
  2544. [TestMethod]
  2545. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2546. {
  2547. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2548. {
  2549. client.Connect();
  2550. var remoteFile = GenerateUniqueRemoteFileName();
  2551. if (client.Exists(remoteFile))
  2552. {
  2553. client.DeleteFile(remoteFile);
  2554. }
  2555. try
  2556. {
  2557. using (var ms = new MemoryStream())
  2558. {
  2559. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2560. try
  2561. {
  2562. client.EndDownloadFile(asyncResult);
  2563. Assert.Fail();
  2564. }
  2565. catch (SftpPathNotFoundException ex)
  2566. {
  2567. Assert.IsNull(ex.InnerException);
  2568. Assert.AreEqual("No such file", ex.Message);
  2569. // ensure file was not created by us
  2570. Assert.IsFalse(client.Exists(remoteFile));
  2571. }
  2572. }
  2573. }
  2574. finally
  2575. {
  2576. if (client.Exists(remoteFile))
  2577. {
  2578. client.DeleteFile(remoteFile);
  2579. }
  2580. }
  2581. }
  2582. }
  2583. [TestMethod]
  2584. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2585. {
  2586. const string remoteDirectory = "/home/sshnet/test123";
  2587. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2588. {
  2589. client.Connect();
  2590. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2591. {
  2592. command.Execute();
  2593. }
  2594. }
  2595. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2596. {
  2597. client.Connect();
  2598. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2599. try
  2600. {
  2601. client.EndListDirectory(asyncResult);
  2602. Assert.Fail();
  2603. }
  2604. catch (SftpPathNotFoundException ex)
  2605. {
  2606. Assert.IsNull(ex.InnerException);
  2607. Assert.AreEqual("No such file", ex.Message);
  2608. // ensure directory was not created by us
  2609. Assert.IsFalse(client.Exists(remoteDirectory));
  2610. }
  2611. }
  2612. }
  2613. [TestMethod]
  2614. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2615. {
  2616. const int size = 50 * 1024 * 1024;
  2617. const string remoteDirectory = "/home/sshnet/test123";
  2618. const string remoteFile = remoteDirectory + "/test";
  2619. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2620. {
  2621. client.Connect();
  2622. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2623. {
  2624. command.Execute();
  2625. }
  2626. }
  2627. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2628. {
  2629. client.Connect();
  2630. var memoryStream = CreateMemoryStream(size);
  2631. memoryStream.Position = 0;
  2632. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2633. try
  2634. {
  2635. client.EndUploadFile(asyncResult);
  2636. Assert.Fail();
  2637. }
  2638. catch (SftpPathNotFoundException)
  2639. {
  2640. }
  2641. }
  2642. }
  2643. [TestMethod]
  2644. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2645. {
  2646. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2647. {
  2648. client.Connect();
  2649. var remoteFile = GenerateUniqueRemoteFileName();
  2650. if (client.Exists(remoteFile))
  2651. {
  2652. client.DeleteFile(remoteFile);
  2653. }
  2654. try
  2655. {
  2656. var uploadMemoryStream = new MemoryStream();
  2657. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2658. sw.Write("Gert & Ann");
  2659. sw.Flush();
  2660. uploadMemoryStream.Position = 0;
  2661. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2662. client.EndUploadFile(asyncResult);
  2663. using (var downloadMemoryStream = new MemoryStream())
  2664. {
  2665. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2666. downloadMemoryStream.Position = 0;
  2667. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2668. {
  2669. var content = sr.ReadToEnd();
  2670. Assert.AreEqual("Gert & Ann", content);
  2671. }
  2672. }
  2673. }
  2674. finally
  2675. {
  2676. if (client.Exists(remoteFile))
  2677. {
  2678. client.DeleteFile(remoteFile);
  2679. }
  2680. }
  2681. }
  2682. }
  2683. [TestMethod]
  2684. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2685. {
  2686. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2687. {
  2688. client.Connect();
  2689. var remoteFile = GenerateUniqueRemoteFileName();
  2690. if (client.Exists(remoteFile))
  2691. {
  2692. client.DeleteFile(remoteFile);
  2693. }
  2694. try
  2695. {
  2696. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2697. var uploadMemoryStream = new MemoryStream();
  2698. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2699. sw.Write("Ann & Gert");
  2700. sw.Flush();
  2701. uploadMemoryStream.Position = 0;
  2702. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2703. client.EndUploadFile(asyncResult);
  2704. using (var downloadMemoryStream = new MemoryStream())
  2705. {
  2706. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2707. downloadMemoryStream.Position = 0;
  2708. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2709. {
  2710. var content = sr.ReadToEnd();
  2711. Assert.AreEqual("Ann & Gert", content);
  2712. }
  2713. }
  2714. }
  2715. finally
  2716. {
  2717. if (client.Exists(remoteFile))
  2718. {
  2719. client.DeleteFile(remoteFile);
  2720. }
  2721. }
  2722. }
  2723. }
  2724. [TestMethod]
  2725. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2726. {
  2727. const int size = 50 * 1024 * 1024;
  2728. const string remoteDirectory = "/home/sshnet/test123";
  2729. const string remoteFile = remoteDirectory + "/test";
  2730. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2731. {
  2732. client.Connect();
  2733. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2734. {
  2735. command.Execute();
  2736. }
  2737. }
  2738. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2739. {
  2740. client.Connect();
  2741. var memoryStream = CreateMemoryStream(size);
  2742. memoryStream.Position = 0;
  2743. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2744. try
  2745. {
  2746. client.EndUploadFile(asyncResult);
  2747. Assert.Fail();
  2748. }
  2749. catch (SftpPathNotFoundException)
  2750. {
  2751. }
  2752. }
  2753. }
  2754. [TestMethod]
  2755. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2756. {
  2757. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2758. {
  2759. client.Connect();
  2760. var remoteFile = GenerateUniqueRemoteFileName();
  2761. if (client.Exists(remoteFile))
  2762. {
  2763. client.DeleteFile(remoteFile);
  2764. }
  2765. try
  2766. {
  2767. using (var uploadMemoryStream = new MemoryStream())
  2768. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2769. {
  2770. sw.Write("Gert & Ann");
  2771. sw.Flush();
  2772. uploadMemoryStream.Position = 0;
  2773. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2774. client.EndUploadFile(asyncResult);
  2775. }
  2776. using (var downloadMemoryStream = new MemoryStream())
  2777. {
  2778. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2779. downloadMemoryStream.Position = 0;
  2780. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2781. {
  2782. var content = sr.ReadToEnd();
  2783. Assert.AreEqual("Gert & Ann", content);
  2784. }
  2785. }
  2786. }
  2787. finally
  2788. {
  2789. if (client.Exists(remoteFile))
  2790. {
  2791. client.DeleteFile(remoteFile);
  2792. }
  2793. }
  2794. }
  2795. }
  2796. [TestMethod]
  2797. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2798. {
  2799. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2800. {
  2801. client.Connect();
  2802. var remoteFile = GenerateUniqueRemoteFileName();
  2803. if (client.Exists(remoteFile))
  2804. {
  2805. client.DeleteFile(remoteFile);
  2806. }
  2807. try
  2808. {
  2809. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2810. var uploadMemoryStream = new MemoryStream();
  2811. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2812. sw.Write("Ann & Gert");
  2813. sw.Flush();
  2814. uploadMemoryStream.Position = 0;
  2815. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2816. try
  2817. {
  2818. client.EndUploadFile(asyncResult);
  2819. Assert.Fail();
  2820. }
  2821. catch (SshException ex)
  2822. {
  2823. Assert.AreEqual(typeof(SshException), ex.GetType());
  2824. Assert.IsNull(ex.InnerException);
  2825. Assert.AreEqual("Failure", ex.Message);
  2826. }
  2827. }
  2828. finally
  2829. {
  2830. if (client.Exists(remoteFile))
  2831. {
  2832. client.DeleteFile(remoteFile);
  2833. }
  2834. }
  2835. }
  2836. }
  2837. [TestMethod]
  2838. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2839. {
  2840. const int size = 50 * 1024 * 1024;
  2841. const string remoteDirectory = "/home/sshnet/test123";
  2842. const string remoteFile = remoteDirectory + "/test";
  2843. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2844. {
  2845. client.Connect();
  2846. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2847. {
  2848. command.Execute();
  2849. }
  2850. }
  2851. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2852. {
  2853. client.Connect();
  2854. var memoryStream = CreateMemoryStream(size);
  2855. memoryStream.Position = 0;
  2856. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2857. try
  2858. {
  2859. client.EndUploadFile(asyncResult);
  2860. Assert.Fail();
  2861. }
  2862. catch (SftpPathNotFoundException)
  2863. {
  2864. }
  2865. }
  2866. }
  2867. [TestMethod]
  2868. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2869. {
  2870. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2871. {
  2872. client.Connect();
  2873. var remoteFile = GenerateUniqueRemoteFileName();
  2874. if (client.Exists(remoteFile))
  2875. {
  2876. client.DeleteFile(remoteFile);
  2877. }
  2878. try
  2879. {
  2880. using (var uploadMemoryStream = new MemoryStream())
  2881. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2882. {
  2883. sw.Write("Gert & Ann");
  2884. sw.Flush();
  2885. uploadMemoryStream.Position = 0;
  2886. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2887. client.EndUploadFile(asyncResult);
  2888. }
  2889. using (var downloadMemoryStream = new MemoryStream())
  2890. {
  2891. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2892. downloadMemoryStream.Position = 0;
  2893. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2894. {
  2895. var content = sr.ReadToEnd();
  2896. Assert.AreEqual("Gert & Ann", content);
  2897. }
  2898. }
  2899. }
  2900. finally
  2901. {
  2902. if (client.Exists(remoteFile))
  2903. {
  2904. client.DeleteFile(remoteFile);
  2905. }
  2906. }
  2907. }
  2908. }
  2909. [TestMethod]
  2910. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2911. {
  2912. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2913. {
  2914. client.Connect();
  2915. var remoteFile = GenerateUniqueRemoteFileName();
  2916. if (client.Exists(remoteFile))
  2917. {
  2918. client.DeleteFile(remoteFile);
  2919. }
  2920. try
  2921. {
  2922. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2923. using (var uploadMemoryStream = new MemoryStream())
  2924. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2925. {
  2926. sw.Write("Ann & Gert");
  2927. sw.Flush();
  2928. uploadMemoryStream.Position = 0;
  2929. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2930. client.EndUploadFile(asyncResult);
  2931. }
  2932. using (var downloadMemoryStream = new MemoryStream())
  2933. {
  2934. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2935. downloadMemoryStream.Position = 0;
  2936. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2937. {
  2938. var content = sr.ReadToEnd();
  2939. Assert.AreEqual("Ann & Gert", content);
  2940. }
  2941. }
  2942. }
  2943. finally
  2944. {
  2945. if (client.Exists(remoteFile))
  2946. {
  2947. client.DeleteFile(remoteFile);
  2948. }
  2949. }
  2950. }
  2951. }
  2952. [TestMethod]
  2953. public void Sftp_UploadAndDownloadBigFile()
  2954. {
  2955. const int size = 50 * 1024 * 1024;
  2956. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2957. {
  2958. client.Connect();
  2959. var remoteFile = GenerateUniqueRemoteFileName();
  2960. if (client.Exists(remoteFile))
  2961. {
  2962. client.Delete(remoteFile);
  2963. }
  2964. try
  2965. {
  2966. var memoryStream = CreateMemoryStream(size);
  2967. memoryStream.Position = 0;
  2968. var expectedHash = CreateHash(memoryStream);
  2969. memoryStream.Position = 0;
  2970. client.UploadFile(memoryStream, remoteFile);
  2971. memoryStream.SetLength(0);
  2972. var stopwatch = new Stopwatch();
  2973. stopwatch.Start();
  2974. client.DownloadFile(remoteFile, memoryStream);
  2975. stopwatch.Stop();
  2976. Assert.AreEqual(size, memoryStream.Length);
  2977. memoryStream.Position = 0;
  2978. var actualHash = CreateHash(memoryStream);
  2979. Assert.AreEqual(expectedHash, actualHash);
  2980. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2981. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2982. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2983. }
  2984. finally
  2985. {
  2986. if (client.Exists(remoteFile))
  2987. {
  2988. client.Delete(remoteFile);
  2989. }
  2990. }
  2991. }
  2992. }
  2993. /// <summary>
  2994. /// Issue 1672
  2995. /// </summary>
  2996. [TestMethod]
  2997. public void Sftp_CurrentWorkingDirectory()
  2998. {
  2999. const string homeDirectory = "/home/sshnet";
  3000. const string otherDirectory = homeDirectory + "/dir";
  3001. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3002. {
  3003. client.Connect();
  3004. if (client.Exists(otherDirectory))
  3005. {
  3006. client.DeleteDirectory(otherDirectory);
  3007. }
  3008. try
  3009. {
  3010. client.CreateDirectory(otherDirectory);
  3011. client.ChangeDirectory(otherDirectory);
  3012. using (var s = CreateStreamWithContent("A"))
  3013. {
  3014. client.UploadFile(s, "a.txt");
  3015. }
  3016. using (var s = new MemoryStream())
  3017. {
  3018. client.DownloadFile("a.txt", s);
  3019. s.Position = 0;
  3020. var content = Encoding.ASCII.GetString(s.ToArray());
  3021. Assert.AreEqual("A", content);
  3022. }
  3023. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  3024. client.DeleteFile("a.txt");
  3025. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  3026. client.DeleteDirectory(".");
  3027. Assert.IsFalse(client.Exists(otherDirectory));
  3028. }
  3029. finally
  3030. {
  3031. if (client.Exists(otherDirectory))
  3032. {
  3033. client.DeleteDirectory(otherDirectory);
  3034. }
  3035. }
  3036. }
  3037. }
  3038. [TestMethod]
  3039. public void Sftp_Exists()
  3040. {
  3041. const string remoteHome = "/home/sshnet";
  3042. #region Setup
  3043. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3044. {
  3045. client.Connect();
  3046. #region Clean-up
  3047. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3048. {
  3049. command.Execute();
  3050. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3051. }
  3052. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3053. {
  3054. command.Execute();
  3055. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3056. }
  3057. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  3058. )
  3059. {
  3060. command.Execute();
  3061. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3062. }
  3063. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3064. {
  3065. command.Execute();
  3066. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3067. }
  3068. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3069. {
  3070. command.Execute();
  3071. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3072. }
  3073. #endregion Clean-up
  3074. #region Setup
  3075. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  3076. {
  3077. command.Execute();
  3078. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3079. }
  3080. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  3081. {
  3082. command.Execute();
  3083. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3084. }
  3085. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  3086. {
  3087. command.Execute();
  3088. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3089. }
  3090. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  3091. {
  3092. command.Execute();
  3093. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3094. }
  3095. #endregion Setup
  3096. }
  3097. #endregion Setup
  3098. #region Assert
  3099. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3100. {
  3101. client.Connect();
  3102. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  3103. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  3104. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  3105. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  3106. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  3107. }
  3108. #endregion Assert
  3109. #region Teardown
  3110. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3111. {
  3112. client.Connect();
  3113. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3114. {
  3115. command.Execute();
  3116. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3117. }
  3118. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3119. {
  3120. command.Execute();
  3121. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3122. }
  3123. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  3124. {
  3125. command.Execute();
  3126. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3127. }
  3128. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3129. {
  3130. command.Execute();
  3131. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3132. }
  3133. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3134. {
  3135. command.Execute();
  3136. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3137. }
  3138. }
  3139. #endregion Teardown
  3140. }
  3141. [TestMethod]
  3142. public async Task Sftp_ExistsAsync()
  3143. {
  3144. const string remoteHome = "/home/sshnet";
  3145. #region Setup
  3146. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3147. {
  3148. client.Connect();
  3149. #region Clean-up
  3150. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3151. {
  3152. await command.ExecuteAsync();
  3153. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3154. }
  3155. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3156. {
  3157. await command.ExecuteAsync();
  3158. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3159. }
  3160. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  3161. )
  3162. {
  3163. await command.ExecuteAsync();
  3164. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3165. }
  3166. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3167. {
  3168. await command.ExecuteAsync();
  3169. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3170. }
  3171. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3172. {
  3173. await command.ExecuteAsync();
  3174. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3175. }
  3176. #endregion Clean-up
  3177. #region Setup
  3178. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  3179. {
  3180. await command.ExecuteAsync();
  3181. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3182. }
  3183. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  3184. {
  3185. await command.ExecuteAsync();
  3186. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3187. }
  3188. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  3189. {
  3190. await command.ExecuteAsync();
  3191. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3192. }
  3193. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  3194. {
  3195. await command.ExecuteAsync();
  3196. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3197. }
  3198. #endregion Setup
  3199. }
  3200. #endregion Setup
  3201. #region Assert
  3202. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3203. {
  3204. await client.ConnectAsync(default).ConfigureAwait(false);
  3205. Assert.IsFalse(await client.ExistsAsync(remoteHome + "/DoesNotExist"));
  3206. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/file.exists"));
  3207. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.file.exists"));
  3208. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/directory.exists"));
  3209. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.directory.exists"));
  3210. }
  3211. #endregion Assert
  3212. #region Teardown
  3213. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3214. {
  3215. client.Connect();
  3216. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3217. {
  3218. await command.ExecuteAsync();
  3219. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3220. }
  3221. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3222. {
  3223. await command.ExecuteAsync();
  3224. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3225. }
  3226. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  3227. {
  3228. await command.ExecuteAsync();
  3229. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3230. }
  3231. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3232. {
  3233. await command.ExecuteAsync();
  3234. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3235. }
  3236. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3237. {
  3238. await command.ExecuteAsync();
  3239. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3240. }
  3241. }
  3242. #endregion Teardown
  3243. }
  3244. [TestMethod]
  3245. public void Sftp_ListDirectory()
  3246. {
  3247. const string remoteDirectory = "/home/sshnet/test123";
  3248. try
  3249. {
  3250. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3251. {
  3252. client.Connect();
  3253. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  3254. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  3255. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  3256. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  3257. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  3258. }
  3259. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3260. {
  3261. client.Connect();
  3262. client.ChangeDirectory(remoteDirectory);
  3263. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3264. Assert.AreEqual(5, directoryContent.Count);
  3265. Assert.AreEqual(".", directoryContent[0].Name);
  3266. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3267. Assert.IsTrue(directoryContent[0].IsDirectory);
  3268. Assert.AreEqual("..", directoryContent[1].Name);
  3269. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3270. Assert.IsTrue(directoryContent[1].IsDirectory);
  3271. Assert.AreEqual("file1", directoryContent[2].Name);
  3272. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3273. Assert.IsFalse(directoryContent[2].IsDirectory);
  3274. Assert.AreEqual("file2", directoryContent[3].Name);
  3275. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3276. Assert.IsFalse(directoryContent[3].IsDirectory);
  3277. Assert.AreEqual("sub", directoryContent[4].Name);
  3278. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3279. Assert.IsTrue(directoryContent[4].IsDirectory);
  3280. }
  3281. }
  3282. finally
  3283. {
  3284. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3285. {
  3286. client.Connect();
  3287. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3288. {
  3289. command.Execute();
  3290. }
  3291. }
  3292. }
  3293. }
  3294. [TestMethod]
  3295. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3296. {
  3297. const string remoteDirectory = "/home/sshnet/test123";
  3298. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3299. {
  3300. client.Connect();
  3301. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3302. {
  3303. command.Execute();
  3304. }
  3305. }
  3306. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3307. {
  3308. client.Connect();
  3309. try
  3310. {
  3311. client.ChangeDirectory(remoteDirectory);
  3312. Assert.Fail();
  3313. }
  3314. catch (SftpPathNotFoundException)
  3315. {
  3316. }
  3317. }
  3318. }
  3319. [TestMethod]
  3320. public async Task Sftp_ChangeDirectory_DirectoryDoesNotExistAsync()
  3321. {
  3322. const string remoteDirectory = "/home/sshnet/test123";
  3323. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3324. {
  3325. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3326. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3327. {
  3328. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3329. }
  3330. }
  3331. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3332. {
  3333. client.Connect();
  3334. try
  3335. {
  3336. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3337. Assert.Fail();
  3338. }
  3339. catch (SftpPathNotFoundException)
  3340. {
  3341. }
  3342. }
  3343. }
  3344. [TestMethod]
  3345. public void Sftp_ChangeDirectory_DirectoryExists()
  3346. {
  3347. const string remoteDirectory = "/home/sshnet/test123";
  3348. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3349. {
  3350. client.Connect();
  3351. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3352. {
  3353. command.Execute();
  3354. }
  3355. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3356. {
  3357. command.Execute();
  3358. }
  3359. }
  3360. try
  3361. {
  3362. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3363. {
  3364. client.Connect();
  3365. client.ChangeDirectory(remoteDirectory);
  3366. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3367. using (var uploadStream = CreateMemoryStream(100))
  3368. {
  3369. uploadStream.Position = 0;
  3370. client.UploadFile(uploadStream, "gert.txt");
  3371. uploadStream.Position = 0;
  3372. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3373. {
  3374. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3375. }
  3376. }
  3377. }
  3378. }
  3379. finally
  3380. {
  3381. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3382. {
  3383. client.Connect();
  3384. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3385. {
  3386. command.Execute();
  3387. }
  3388. }
  3389. }
  3390. }
  3391. [TestMethod]
  3392. public async Task Sftp_ChangeDirectory_DirectoryExistsAsync()
  3393. {
  3394. const string remoteDirectory = "/home/sshnet/test123";
  3395. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3396. {
  3397. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3398. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3399. {
  3400. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3401. }
  3402. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3403. {
  3404. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3405. }
  3406. }
  3407. try
  3408. {
  3409. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3410. {
  3411. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3412. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3413. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3414. using (var uploadStream = CreateMemoryStream(100))
  3415. {
  3416. uploadStream.Position = 0;
  3417. await client.UploadFileAsync(uploadStream, "gert.txt").ConfigureAwait(false);
  3418. uploadStream.Position = 0;
  3419. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3420. {
  3421. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3422. }
  3423. }
  3424. }
  3425. }
  3426. finally
  3427. {
  3428. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3429. {
  3430. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3431. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3432. {
  3433. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3434. }
  3435. }
  3436. }
  3437. }
  3438. [TestMethod]
  3439. public void Sftp_SubsystemExecution_Failed()
  3440. {
  3441. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3442. // Disable SFTP subsystem
  3443. remoteSshdConfig.ClearSubsystems()
  3444. .Update()
  3445. .Restart();
  3446. var remoteSshdReconfiguredToDefaultState = false;
  3447. try
  3448. {
  3449. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3450. {
  3451. try
  3452. {
  3453. client.Connect();
  3454. Assert.Fail("Establishing SFTP connection should have failed.");
  3455. }
  3456. catch (SshException ex)
  3457. {
  3458. Assert.IsNull(ex.InnerException);
  3459. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3460. }
  3461. // Re-enable SFTP subsystem
  3462. remoteSshdConfig.Reset();
  3463. remoteSshdReconfiguredToDefaultState = true;
  3464. // ensure we can reconnect the same SftpClient instance
  3465. client.Connect();
  3466. // ensure SFTP session is correctly established
  3467. Assert.IsTrue(client.Exists("."));
  3468. }
  3469. }
  3470. finally
  3471. {
  3472. if (!remoteSshdReconfiguredToDefaultState)
  3473. {
  3474. remoteSshdConfig.Reset();
  3475. }
  3476. }
  3477. }
  3478. [TestMethod]
  3479. public void Sftp_SftpFileStream_ReadAndWrite()
  3480. {
  3481. TestReadAndWrite(
  3482. (s, buffer, offset, count) => s.Read(buffer, offset, count),
  3483. (s, buffer, offset, count) => s.Write(buffer, offset, count));
  3484. }
  3485. [TestMethod]
  3486. public void Sftp_SftpFileStream_ReadAndWriteByte()
  3487. {
  3488. TestReadAndWrite(
  3489. read: (s, buffer, offset, count) =>
  3490. {
  3491. int bytesRead = 0;
  3492. int b;
  3493. while (bytesRead < count && (b = s.ReadByte()) != -1)
  3494. {
  3495. buffer[offset + bytesRead] = (byte)b;
  3496. bytesRead++;
  3497. }
  3498. return bytesRead;
  3499. },
  3500. write: (s, buffer, offset, count) =>
  3501. {
  3502. for (int i = 0; i < count; i++)
  3503. {
  3504. s.WriteByte(buffer[offset + i]);
  3505. }
  3506. });
  3507. }
  3508. [TestMethod]
  3509. public void Sftp_SftpFileStream_ReadAndWriteAsync()
  3510. {
  3511. TestReadAndWrite(
  3512. (s, buffer, offset, count) => s.ReadAsync(buffer, offset, count).GetAwaiter().GetResult(),
  3513. (s, buffer, offset, count) => s.WriteAsync(buffer, offset, count).GetAwaiter().GetResult());
  3514. }
  3515. [TestMethod]
  3516. public void Sftp_SftpFileStream_ReadAndWriteBeginEnd()
  3517. {
  3518. TestReadAndWrite(
  3519. (s, buffer, offset, count) => s.EndRead(s.BeginRead(buffer, offset, count, null, null)),
  3520. (s, buffer, offset, count) => s.EndWrite(s.BeginWrite(buffer, offset, count, null, null)));
  3521. }
  3522. #if NET
  3523. [TestMethod]
  3524. public void Sftp_SftpFileStream_ReadAndWriteSpan()
  3525. {
  3526. TestReadAndWrite(
  3527. (s, buffer, offset, count) => s.Read(buffer.AsSpan(offset, count)),
  3528. (s, buffer, offset, count) => s.Write(buffer.AsSpan(offset, count)));
  3529. }
  3530. [TestMethod]
  3531. public void Sftp_SftpFileStream_ReadAndWriteAsyncMemory()
  3532. {
  3533. TestReadAndWrite(
  3534. (s, buffer, offset, count) => s.ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(),
  3535. (s, buffer, offset, count) => s.WriteAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult());
  3536. }
  3537. #endif
  3538. private void TestReadAndWrite(
  3539. Func<SftpFileStream, byte[], int, int, int> read,
  3540. Action<SftpFileStream, byte[], int, int> write)
  3541. {
  3542. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3543. {
  3544. client.Connect();
  3545. var remoteFile = GenerateUniqueRemoteFileName();
  3546. if (client.Exists(remoteFile))
  3547. {
  3548. client.DeleteFile(remoteFile);
  3549. }
  3550. try
  3551. {
  3552. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3553. {
  3554. Assert.IsFalse(s.CanRead);
  3555. Assert.IsTrue(s.CanWrite);
  3556. write(s, new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3557. }
  3558. // switch from read to write mode
  3559. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3560. {
  3561. Assert.IsTrue(s.CanRead);
  3562. Assert.IsTrue(s.CanWrite);
  3563. Assert.AreEqual(4, ReadByte(s));
  3564. Assert.AreEqual(3, ReadByte(s));
  3565. Assert.AreEqual(2, s.Position);
  3566. WriteByte(s, 7);
  3567. write(s, new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3568. Assert.AreEqual(6, s.Position);
  3569. }
  3570. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3571. {
  3572. Assert.IsTrue(s.CanRead);
  3573. Assert.IsFalse(s.CanWrite);
  3574. Assert.AreEqual(6, s.Length);
  3575. var buffer = new byte[s.Length];
  3576. Assert.AreEqual(6, read(s, buffer, 0, buffer.Length));
  3577. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3578. // Ensure we've reached end of the stream
  3579. Assert.AreEqual(-1, ReadByte(s));
  3580. }
  3581. // switch from read to write mode, and back to read mode and finally
  3582. // append a byte
  3583. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3584. {
  3585. Assert.AreEqual(4, ReadByte(s));
  3586. Assert.AreEqual(3, ReadByte(s));
  3587. Assert.AreEqual(7, ReadByte(s));
  3588. write(s, new byte[] { 0, 1, 6, 4 }, 1, 2);
  3589. Assert.AreEqual(11, ReadByte(s));
  3590. // Ensure we've reached end of the stream
  3591. Assert.AreEqual(-1, ReadByte(s));
  3592. WriteByte(s, 12);
  3593. }
  3594. // switch from write to read mode, and back to write mode
  3595. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3596. {
  3597. WriteByte(s, 5);
  3598. Assert.AreEqual(3, ReadByte(s));
  3599. WriteByte(s, 13);
  3600. Assert.AreEqual(3, s.Position);
  3601. }
  3602. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3603. {
  3604. Assert.AreEqual(7, s.Length);
  3605. var buffer = new byte[s.Length];
  3606. Assert.AreEqual(7, read(s, buffer, 0, buffer.Length));
  3607. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3608. // Ensure we've reached end of the stream
  3609. Assert.AreEqual(-1, ReadByte(s));
  3610. }
  3611. }
  3612. finally
  3613. {
  3614. if (client.Exists(remoteFile))
  3615. {
  3616. client.DeleteFile(remoteFile);
  3617. }
  3618. }
  3619. }
  3620. int ReadByte(SftpFileStream s)
  3621. {
  3622. var buffer = new byte[1];
  3623. var bytesRead = read(s, buffer, 0, 1);
  3624. return bytesRead == 0 ? -1 : buffer[0];
  3625. }
  3626. void WriteByte(SftpFileStream s, byte b)
  3627. {
  3628. write(s, [b], 0, 1);
  3629. }
  3630. }
  3631. [TestMethod]
  3632. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3633. {
  3634. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3635. {
  3636. client.Connect();
  3637. var remoteFile = GenerateUniqueRemoteFileName();
  3638. if (client.Exists(remoteFile))
  3639. {
  3640. client.DeleteFile(remoteFile);
  3641. }
  3642. try
  3643. {
  3644. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3645. {
  3646. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3647. }
  3648. // reduce length while in write mode, with data in write buffer, and before
  3649. // current position
  3650. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3651. {
  3652. s.Position = 3;
  3653. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3654. Assert.AreEqual(7, s.Position);
  3655. // verify buffer has not yet been flushed
  3656. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3657. {
  3658. Assert.AreEqual(4, fs.ReadByte());
  3659. Assert.AreEqual(3, fs.ReadByte());
  3660. Assert.AreEqual(2, fs.ReadByte());
  3661. // Ensure we've reached end of the stream
  3662. Assert.AreEqual(-1, fs.ReadByte());
  3663. }
  3664. s.SetLength(5);
  3665. Assert.AreEqual(5, s.Position);
  3666. // verify that buffer was flushed and size has been modified
  3667. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3668. {
  3669. Assert.AreEqual(4, fs.ReadByte());
  3670. Assert.AreEqual(3, fs.ReadByte());
  3671. Assert.AreEqual(2, fs.ReadByte());
  3672. Assert.AreEqual(6, fs.ReadByte());
  3673. Assert.AreEqual(7, fs.ReadByte());
  3674. // Ensure we've reached end of the stream
  3675. Assert.AreEqual(-1, fs.ReadByte());
  3676. }
  3677. s.WriteByte(1);
  3678. }
  3679. // verify that last byte was correctly written to the file
  3680. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3681. {
  3682. Assert.AreEqual(6, s.Length);
  3683. var buffer = new byte[s.Length + 2];
  3684. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3685. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3686. // Ensure we've reached end of the stream
  3687. Assert.AreEqual(-1, s.ReadByte());
  3688. }
  3689. // reduce length while in read mode, but beyond current position
  3690. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3691. {
  3692. var buffer = new byte[1];
  3693. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3694. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3695. s.SetLength(3);
  3696. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3697. {
  3698. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3699. }
  3700. // verify that position was not changed
  3701. Assert.AreEqual(1, s.Position);
  3702. // verify that read buffer was cleared
  3703. Assert.AreEqual(1, s.ReadByte());
  3704. Assert.AreEqual(6, s.ReadByte());
  3705. Assert.AreEqual(2, s.ReadByte());
  3706. // Ensure we've reached end of the stream
  3707. Assert.AreEqual(-1, s.ReadByte());
  3708. Assert.AreEqual(4, s.Length);
  3709. }
  3710. // reduce length while in read mode, but before current position
  3711. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3712. {
  3713. var buffer = new byte[4];
  3714. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3715. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3716. Assert.AreEqual(4, s.Position);
  3717. s.SetLength(3);
  3718. // verify that position was moved to last byte
  3719. Assert.AreEqual(3, s.Position);
  3720. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3721. {
  3722. Assert.AreEqual(3, w.Length);
  3723. Assert.AreEqual(8, w.ReadByte());
  3724. Assert.AreEqual(1, w.ReadByte());
  3725. Assert.AreEqual(6, w.ReadByte());
  3726. // Ensure we've reached end of the stream
  3727. Assert.AreEqual(-1, w.ReadByte());
  3728. }
  3729. // Ensure we've reached end of the stream
  3730. Assert.AreEqual(-1, s.ReadByte());
  3731. }
  3732. }
  3733. finally
  3734. {
  3735. if (client.Exists(remoteFile))
  3736. {
  3737. client.DeleteFile(remoteFile);
  3738. }
  3739. }
  3740. }
  3741. }
  3742. [TestMethod]
  3743. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3744. {
  3745. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3746. {
  3747. client.BufferSize = 500;
  3748. client.Connect();
  3749. var remoteFile = GenerateUniqueRemoteFileName();
  3750. if (client.Exists(remoteFile))
  3751. {
  3752. client.DeleteFile(remoteFile);
  3753. }
  3754. try
  3755. {
  3756. // create single-byte file
  3757. using (var fs = client.OpenWrite(remoteFile))
  3758. {
  3759. fs.WriteByte(0x04);
  3760. }
  3761. // seek beyond EOF but not beyond buffer size
  3762. // do not write anything
  3763. using (var fs = client.OpenWrite(remoteFile))
  3764. {
  3765. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3766. Assert.AreEqual(3, newPosition);
  3767. Assert.AreEqual(3, fs.Position);
  3768. Assert.AreEqual(1, fs.Length);
  3769. }
  3770. using (var fs = client.OpenRead(remoteFile))
  3771. {
  3772. Assert.AreEqual(1, fs.Length);
  3773. Assert.AreEqual(0x04, fs.ReadByte());
  3774. // Ensure we've reached end of the stream
  3775. Assert.AreEqual(-1, fs.ReadByte());
  3776. }
  3777. client.DeleteFile(remoteFile);
  3778. // create single-byte file
  3779. using (var fs = client.OpenWrite(remoteFile))
  3780. {
  3781. fs.WriteByte(0x04);
  3782. }
  3783. // seek beyond EOF and beyond buffer size
  3784. // do not write anything
  3785. using (var fs = client.OpenWrite(remoteFile))
  3786. {
  3787. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3788. Assert.AreEqual(700, newPosition);
  3789. Assert.AreEqual(700, fs.Position);
  3790. Assert.AreEqual(1, fs.Length);
  3791. }
  3792. using (var fs = client.OpenRead(remoteFile))
  3793. {
  3794. Assert.AreEqual(1, fs.Length);
  3795. Assert.AreEqual(0x04, fs.ReadByte());
  3796. // Ensure we've reached end of the stream
  3797. Assert.AreEqual(-1, fs.ReadByte());
  3798. }
  3799. client.DeleteFile(remoteFile);
  3800. // create single-byte file
  3801. using (var fs = client.OpenWrite(remoteFile))
  3802. {
  3803. fs.WriteByte(0x04);
  3804. }
  3805. // seek beyond EOF but not beyond buffer size
  3806. // write less bytes than buffer size
  3807. var seekOffset = 3L;
  3808. // buffer holding the data that we'll write to the file
  3809. var writeBuffer = GenerateRandom(size: 7);
  3810. using (var fs = client.OpenWrite(remoteFile))
  3811. {
  3812. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3813. Assert.AreEqual(seekOffset, newPosition);
  3814. Assert.AreEqual(seekOffset, fs.Position);
  3815. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3816. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3817. }
  3818. using (var fs = client.OpenRead(remoteFile))
  3819. {
  3820. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3821. Assert.AreEqual(0x04, fs.ReadByte());
  3822. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3823. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3824. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3825. var readBuffer = new byte[writeBuffer.Length];
  3826. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3827. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3828. // Ensure we've reached end of the stream
  3829. Assert.AreEqual(-1, fs.ReadByte());
  3830. }
  3831. client.DeleteFile(remoteFile);
  3832. // create single-byte file
  3833. using (var fs = client.OpenWrite(remoteFile))
  3834. {
  3835. fs.WriteByte(0x04);
  3836. }
  3837. // seek beyond EOF and beyond buffer size
  3838. // write less bytes than buffer size
  3839. seekOffset = 700L;
  3840. // buffer holding the data that we'll write to the file
  3841. writeBuffer = GenerateRandom(size: 4);
  3842. using (var fs = client.OpenWrite(remoteFile))
  3843. {
  3844. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3845. Assert.AreEqual(seekOffset, newPosition);
  3846. Assert.AreEqual(seekOffset, fs.Position);
  3847. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3848. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3849. }
  3850. using (var fs = client.OpenRead(remoteFile))
  3851. {
  3852. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3853. Assert.AreEqual(0x04, fs.ReadByte());
  3854. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3855. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3856. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3857. var readBuffer = new byte[writeBuffer.Length];
  3858. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3859. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3860. // Ensure we've reached end of the stream
  3861. Assert.AreEqual(-1, fs.ReadByte());
  3862. }
  3863. client.DeleteFile(remoteFile);
  3864. // create single-byte file
  3865. using (var fs = client.OpenWrite(remoteFile))
  3866. {
  3867. fs.WriteByte(0x04);
  3868. }
  3869. // seek beyond EOF but not beyond buffer size
  3870. // write more bytes than buffer size
  3871. writeBuffer = GenerateRandom(size: 600);
  3872. using (var fs = client.OpenWrite(remoteFile))
  3873. {
  3874. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3875. Assert.AreEqual(3, newPosition);
  3876. Assert.AreEqual(3, fs.Position);
  3877. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3878. }
  3879. using (var fs = client.OpenRead(remoteFile))
  3880. {
  3881. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3882. Assert.AreEqual(0x04, fs.ReadByte());
  3883. Assert.AreEqual(0x00, fs.ReadByte());
  3884. Assert.AreEqual(0x00, fs.ReadByte());
  3885. var readBuffer = new byte[writeBuffer.Length];
  3886. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3887. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3888. // Ensure we've reached end of the stream
  3889. Assert.AreEqual(-1, fs.ReadByte());
  3890. }
  3891. client.DeleteFile(remoteFile);
  3892. // create single-byte file
  3893. using (var fs = client.OpenWrite(remoteFile))
  3894. {
  3895. fs.WriteByte(0x04);
  3896. }
  3897. // seek beyond EOF and beyond buffer size
  3898. // write more bytes than buffer size
  3899. writeBuffer = GenerateRandom(size: 600);
  3900. using (var fs = client.OpenWrite(remoteFile))
  3901. {
  3902. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3903. Assert.AreEqual(550, newPosition);
  3904. Assert.AreEqual(550, fs.Position);
  3905. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3906. }
  3907. using (var fs = client.OpenRead(remoteFile))
  3908. {
  3909. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3910. Assert.AreEqual(0x04, fs.ReadByte());
  3911. var soughtOverReadBuffer = new byte[550 - 1];
  3912. Assert.AreEqual(550 - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3913. Assert.IsTrue(new byte[550 - 1].IsEqualTo(soughtOverReadBuffer));
  3914. var readBuffer = new byte[writeBuffer.Length];
  3915. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3916. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3917. // Ensure we've reached end of the stream
  3918. Assert.AreEqual(-1, fs.ReadByte());
  3919. }
  3920. }
  3921. finally
  3922. {
  3923. if (client.Exists(remoteFile))
  3924. {
  3925. client.DeleteFile(remoteFile);
  3926. }
  3927. }
  3928. }
  3929. }
  3930. [TestMethod]
  3931. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3932. {
  3933. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3934. {
  3935. client.BufferSize = 500;
  3936. client.Connect();
  3937. var remoteFile = GenerateUniqueRemoteFileName();
  3938. if (client.Exists(remoteFile))
  3939. {
  3940. client.DeleteFile(remoteFile);
  3941. }
  3942. try
  3943. {
  3944. // create single-byte file
  3945. using (var fs = client.OpenWrite(remoteFile))
  3946. {
  3947. fs.WriteByte(0x04);
  3948. }
  3949. // seek beyond EOF but not beyond buffer size
  3950. // do not write anything
  3951. using (var fs = client.OpenWrite(remoteFile))
  3952. {
  3953. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3954. Assert.AreEqual(4, newPosition);
  3955. Assert.AreEqual(4, fs.Position);
  3956. Assert.AreEqual(1, fs.Length);
  3957. }
  3958. using (var fs = client.OpenRead(remoteFile))
  3959. {
  3960. Assert.AreEqual(1, fs.Length);
  3961. Assert.AreEqual(0x04, fs.ReadByte());
  3962. // Ensure we've reached end of the stream
  3963. Assert.AreEqual(-1, fs.ReadByte());
  3964. }
  3965. client.DeleteFile(remoteFile);
  3966. // create single-byte file
  3967. using (var fs = client.OpenWrite(remoteFile))
  3968. {
  3969. fs.WriteByte(0x04);
  3970. }
  3971. // seek beyond EOF and beyond buffer size
  3972. // do not write anything
  3973. using (var fs = client.OpenWrite(remoteFile))
  3974. {
  3975. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3976. Assert.AreEqual(701, newPosition);
  3977. Assert.AreEqual(701, fs.Position);
  3978. Assert.AreEqual(1, fs.Length);
  3979. }
  3980. using (var fs = client.OpenRead(remoteFile))
  3981. {
  3982. Assert.AreEqual(1, fs.Length);
  3983. Assert.AreEqual(0x04, fs.ReadByte());
  3984. // Ensure we've reached end of the stream
  3985. Assert.AreEqual(-1, fs.ReadByte());
  3986. }
  3987. client.DeleteFile(remoteFile);
  3988. // create single-byte file
  3989. using (var fs = client.OpenWrite(remoteFile))
  3990. {
  3991. fs.WriteByte(0x04);
  3992. }
  3993. // seek beyond EOF but not beyond buffer size
  3994. // write less bytes than buffer size
  3995. var seekOffset = 3L;
  3996. // buffer holding the data that we'll write to the file
  3997. var writeBuffer = GenerateRandom(size: 7);
  3998. using (var fs = client.OpenWrite(remoteFile))
  3999. {
  4000. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  4001. Assert.AreEqual(4, newPosition);
  4002. Assert.AreEqual(4, fs.Position);
  4003. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4004. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  4005. }
  4006. using (var fs = client.OpenRead(remoteFile))
  4007. {
  4008. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  4009. Assert.AreEqual(0x04, fs.ReadByte());
  4010. var soughtOverReadBuffer = new byte[seekOffset];
  4011. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4012. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4013. var readBuffer = new byte[writeBuffer.Length];
  4014. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4015. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4016. // Ensure we've reached end of the stream
  4017. Assert.AreEqual(-1, fs.ReadByte());
  4018. }
  4019. client.DeleteFile(remoteFile);
  4020. // create single-byte file
  4021. using (var fs = client.OpenWrite(remoteFile))
  4022. {
  4023. fs.WriteByte(0x04);
  4024. }
  4025. // seek beyond EOF and beyond buffer size
  4026. // write less bytes than buffer size
  4027. seekOffset = 700L;
  4028. // buffer holding the data that we'll write to the file
  4029. writeBuffer = GenerateRandom(size: 4);
  4030. using (var fs = client.OpenWrite(remoteFile))
  4031. {
  4032. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  4033. Assert.AreEqual(1 + seekOffset, newPosition);
  4034. Assert.AreEqual(1 + seekOffset, fs.Position);
  4035. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4036. }
  4037. using (var fs = client.OpenRead(remoteFile))
  4038. {
  4039. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  4040. Assert.AreEqual(0x04, fs.ReadByte());
  4041. var soughtOverReadBuffer = new byte[seekOffset];
  4042. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4043. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4044. var readBuffer = new byte[writeBuffer.Length];
  4045. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4046. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4047. // Ensure we've reached end of the stream
  4048. Assert.AreEqual(-1, fs.ReadByte());
  4049. }
  4050. client.DeleteFile(remoteFile);
  4051. // create single-byte file
  4052. using (var fs = client.OpenWrite(remoteFile))
  4053. {
  4054. fs.WriteByte(0x04);
  4055. }
  4056. // seek beyond EOF but not beyond buffer size
  4057. // write more bytes than buffer size
  4058. seekOffset = 3L;
  4059. writeBuffer = GenerateRandom(size: 600);
  4060. using (var fs = client.OpenWrite(remoteFile))
  4061. {
  4062. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  4063. Assert.AreEqual(1 + seekOffset, newPosition);
  4064. Assert.AreEqual(1 + seekOffset, fs.Position);
  4065. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4066. }
  4067. using (var fs = client.OpenRead(remoteFile))
  4068. {
  4069. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  4070. Assert.AreEqual(0x04, fs.ReadByte());
  4071. var soughtOverReadBuffer = new byte[seekOffset];
  4072. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4073. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4074. var readBuffer = new byte[writeBuffer.Length];
  4075. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4076. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4077. // Ensure we've reached end of the stream
  4078. Assert.AreEqual(-1, fs.ReadByte());
  4079. }
  4080. client.DeleteFile(remoteFile);
  4081. // create single-byte file
  4082. using (var fs = client.OpenWrite(remoteFile))
  4083. {
  4084. fs.WriteByte(0x04);
  4085. }
  4086. // seek beyond EOF and beyond buffer size
  4087. // write more bytes than buffer size
  4088. seekOffset = 550L;
  4089. writeBuffer = GenerateRandom(size: 600);
  4090. using (var fs = client.OpenWrite(remoteFile))
  4091. {
  4092. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  4093. Assert.AreEqual(1 + seekOffset, newPosition);
  4094. Assert.AreEqual(1 + seekOffset, fs.Position);
  4095. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4096. }
  4097. using (var fs = client.OpenRead(remoteFile))
  4098. {
  4099. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  4100. Assert.AreEqual(0x04, fs.ReadByte());
  4101. var soughtOverReadBuffer = new byte[seekOffset];
  4102. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4103. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4104. var readBuffer = new byte[writeBuffer.Length];
  4105. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4106. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4107. // Ensure we've reached end of the stream
  4108. Assert.AreEqual(-1, fs.ReadByte());
  4109. }
  4110. }
  4111. finally
  4112. {
  4113. if (client.Exists(remoteFile))
  4114. {
  4115. client.DeleteFile(remoteFile);
  4116. }
  4117. }
  4118. }
  4119. }
  4120. [TestMethod]
  4121. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  4122. {
  4123. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4124. {
  4125. client.BufferSize = 500;
  4126. client.Connect();
  4127. var remoteFile = GenerateUniqueRemoteFileName();
  4128. if (client.Exists(remoteFile))
  4129. {
  4130. client.DeleteFile(remoteFile);
  4131. }
  4132. try
  4133. {
  4134. using (var fs = client.OpenWrite(remoteFile))
  4135. {
  4136. fs.WriteByte(0x04);
  4137. fs.WriteByte(0x07);
  4138. fs.WriteByte(0x05);
  4139. }
  4140. // seek within file and not beyond buffer size
  4141. // do not write anything
  4142. using (var fs = client.OpenWrite(remoteFile))
  4143. {
  4144. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  4145. Assert.AreEqual(1, newPosition);
  4146. Assert.AreEqual(1, fs.Position);
  4147. }
  4148. using (var fs = client.OpenRead(remoteFile))
  4149. {
  4150. Assert.AreEqual(3, fs.Length);
  4151. Assert.AreEqual(0x04, fs.ReadByte());
  4152. Assert.AreEqual(0x07, fs.ReadByte());
  4153. Assert.AreEqual(0x05, fs.ReadByte());
  4154. // Ensure we've reached end of the stream
  4155. Assert.AreEqual(-1, fs.ReadByte());
  4156. }
  4157. client.DeleteFile(remoteFile);
  4158. // buffer holding the data that we'll write to the file
  4159. var writeBuffer = GenerateRandom(size: (int)client.BufferSize + 200);
  4160. using (var fs = client.OpenWrite(remoteFile))
  4161. {
  4162. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4163. }
  4164. // seek within EOF and beyond buffer size
  4165. // do not write anything
  4166. using (var fs = client.OpenWrite(remoteFile))
  4167. {
  4168. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  4169. Assert.AreEqual(600, newPosition);
  4170. Assert.AreEqual(600, fs.Position);
  4171. }
  4172. using (var fs = client.OpenRead(remoteFile))
  4173. {
  4174. Assert.AreEqual(writeBuffer.Length, fs.Length);
  4175. var readBuffer = new byte[writeBuffer.Length];
  4176. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4177. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4178. // Ensure we've reached end of the stream
  4179. Assert.AreEqual(-1, fs.ReadByte());
  4180. }
  4181. client.DeleteFile(remoteFile);
  4182. // seek within EOF and within buffer size
  4183. // write less bytes than buffer size
  4184. using (var fs = client.OpenWrite(remoteFile))
  4185. {
  4186. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4187. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  4188. Assert.AreEqual(697, newPosition);
  4189. Assert.AreEqual(697, fs.Position);
  4190. fs.WriteByte(0x01);
  4191. fs.WriteByte(0x05);
  4192. fs.WriteByte(0x04);
  4193. fs.WriteByte(0x07);
  4194. }
  4195. using (var fs = client.OpenRead(remoteFile))
  4196. {
  4197. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  4198. var readBuffer = new byte[writeBuffer.Length - 3];
  4199. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4200. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  4201. Assert.AreEqual(0x01, fs.ReadByte());
  4202. Assert.AreEqual(0x05, fs.ReadByte());
  4203. Assert.AreEqual(0x04, fs.ReadByte());
  4204. Assert.AreEqual(0x07, fs.ReadByte());
  4205. // Ensure we've reached end of the stream
  4206. Assert.AreEqual(-1, fs.ReadByte());
  4207. }
  4208. client.DeleteFile(remoteFile);
  4209. // buffer holding the data that we'll write to the file
  4210. writeBuffer = GenerateRandom(size: (int)client.BufferSize * 4);
  4211. // seek within EOF and beyond buffer size
  4212. // write less bytes than buffer size
  4213. using (var fs = client.OpenWrite(remoteFile))
  4214. {
  4215. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4216. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  4217. Assert.AreEqual(1000, newPosition);
  4218. Assert.AreEqual(1000, fs.Position);
  4219. fs.WriteByte(0x01);
  4220. fs.WriteByte(0x05);
  4221. fs.WriteByte(0x04);
  4222. fs.WriteByte(0x07);
  4223. }
  4224. using (var fs = client.OpenRead(remoteFile))
  4225. {
  4226. Assert.AreEqual(writeBuffer.Length, fs.Length);
  4227. // First part of file should not have been touched
  4228. var readBuffer = new byte[(int)client.BufferSize * 2];
  4229. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4230. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  4231. // Check part that should have been updated
  4232. Assert.AreEqual(0x01, fs.ReadByte());
  4233. Assert.AreEqual(0x05, fs.ReadByte());
  4234. Assert.AreEqual(0x04, fs.ReadByte());
  4235. Assert.AreEqual(0x07, fs.ReadByte());
  4236. // Remaining bytes should not have been touched
  4237. readBuffer = new byte[((int)client.BufferSize * 2) - 4];
  4238. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4239. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length)));
  4240. // Ensure we've reached end of the stream
  4241. Assert.AreEqual(-1, fs.ReadByte());
  4242. }
  4243. }
  4244. finally
  4245. {
  4246. if (client.Exists(remoteFile))
  4247. {
  4248. client.DeleteFile(remoteFile);
  4249. }
  4250. }
  4251. }
  4252. }
  4253. /// https://github.com/sshnet/SSH.NET/issues/253
  4254. [TestMethod]
  4255. public void Sftp_SftpFileStream_Seek_Issue253()
  4256. {
  4257. var buf = Encoding.UTF8.GetBytes("123456");
  4258. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4259. {
  4260. client.Connect();
  4261. var remoteFile = GenerateUniqueRemoteFileName();
  4262. if (client.Exists(remoteFile))
  4263. {
  4264. client.DeleteFile(remoteFile);
  4265. }
  4266. try
  4267. {
  4268. using (var ws = client.OpenWrite(remoteFile))
  4269. {
  4270. ws.Write(buf, offset: 0, count: 3);
  4271. }
  4272. using (var ws = client.OpenWrite(remoteFile))
  4273. {
  4274. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4275. Assert.AreEqual(3, newPosition);
  4276. Assert.AreEqual(3, ws.Position);
  4277. ws.Write(buf, 3, 3);
  4278. }
  4279. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4280. Assert.AreEqual("123456", actual);
  4281. }
  4282. finally
  4283. {
  4284. if (client.Exists(remoteFile))
  4285. {
  4286. client.DeleteFile(remoteFile);
  4287. }
  4288. }
  4289. }
  4290. }
  4291. [TestMethod]
  4292. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4293. {
  4294. var originalContent = GenerateRandom(size: 800);
  4295. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4296. {
  4297. client.BufferSize = 500;
  4298. client.Connect();
  4299. var remoteFile = GenerateUniqueRemoteFileName();
  4300. if (client.Exists(remoteFile))
  4301. {
  4302. client.DeleteFile(remoteFile);
  4303. }
  4304. try
  4305. {
  4306. using (var fs = client.OpenWrite(remoteFile))
  4307. {
  4308. fs.Write(originalContent, offset: 0, originalContent.Length);
  4309. }
  4310. using (var fs = client.OpenRead(remoteFile))
  4311. {
  4312. var readBuffer = new byte[200];
  4313. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4314. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4315. Assert.AreEqual(3L, newPosition);
  4316. Assert.AreEqual(3L, fs.Position);
  4317. }
  4318. client.DeleteFile(remoteFile);
  4319. #region Seek beyond EOF and beyond buffer size do not write anything
  4320. // create single-byte file
  4321. using (var fs = client.OpenWrite(remoteFile))
  4322. {
  4323. fs.WriteByte(0x04);
  4324. }
  4325. using (var fs = client.OpenRead(remoteFile))
  4326. {
  4327. Assert.AreEqual(1, fs.Length);
  4328. Assert.AreEqual(0x04, fs.ReadByte());
  4329. // Ensure we've reached end of the stream
  4330. Assert.AreEqual(-1, fs.ReadByte());
  4331. }
  4332. using (var fs = client.OpenWrite(remoteFile))
  4333. {
  4334. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4335. Assert.AreEqual(700L, newPosition);
  4336. Assert.AreEqual(700L, fs.Position);
  4337. }
  4338. using (var fs = client.OpenRead(remoteFile))
  4339. {
  4340. Assert.AreEqual(1, fs.Length);
  4341. Assert.AreEqual(0x04, fs.ReadByte());
  4342. // Ensure we've reached end of the stream
  4343. Assert.AreEqual(-1, fs.ReadByte());
  4344. }
  4345. client.DeleteFile(remoteFile);
  4346. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4347. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4348. // create single-byte file
  4349. using (var fs = client.OpenWrite(remoteFile))
  4350. {
  4351. fs.WriteByte(0x04);
  4352. }
  4353. var seekOffset = 3L;
  4354. var writeBuffer = GenerateRandom(size: 7);
  4355. using (var fs = client.OpenWrite(remoteFile))
  4356. {
  4357. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4358. Assert.AreEqual(seekOffset, newPosition);
  4359. Assert.AreEqual(seekOffset, fs.Position);
  4360. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4361. }
  4362. using (var fs = client.OpenRead(remoteFile))
  4363. {
  4364. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4365. Assert.AreEqual(0x04, fs.ReadByte());
  4366. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4367. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4368. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4369. var readBuffer = new byte[writeBuffer.Length];
  4370. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4371. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4372. // Ensure we've reached end of the stream
  4373. Assert.AreEqual(-1, fs.ReadByte());
  4374. }
  4375. client.DeleteFile(remoteFile);
  4376. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4377. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4378. // create single-byte file
  4379. using (var fs = client.OpenWrite(remoteFile))
  4380. {
  4381. fs.WriteByte(0x04);
  4382. }
  4383. seekOffset = 700L;
  4384. writeBuffer = GenerateRandom(size: 4);
  4385. using (var fs = client.OpenWrite(remoteFile))
  4386. {
  4387. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4388. Assert.AreEqual(seekOffset, newPosition);
  4389. Assert.AreEqual(seekOffset, fs.Position);
  4390. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4391. }
  4392. using (var fs = client.OpenRead(remoteFile))
  4393. {
  4394. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4395. Assert.AreEqual(0x04, fs.ReadByte());
  4396. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4397. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4398. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4399. var readBuffer = new byte[writeBuffer.Length];
  4400. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4401. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4402. // Ensure we've reached end of the stream
  4403. Assert.AreEqual(-1, fs.ReadByte());
  4404. }
  4405. client.DeleteFile(remoteFile);
  4406. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4407. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4408. // create single-byte file
  4409. using (var fs = client.OpenWrite(remoteFile))
  4410. {
  4411. fs.WriteByte(0x04);
  4412. }
  4413. seekOffset = 3L;
  4414. writeBuffer = GenerateRandom(size: 600);
  4415. using (var fs = client.OpenWrite(remoteFile))
  4416. {
  4417. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4418. Assert.AreEqual(seekOffset, newPosition);
  4419. Assert.AreEqual(seekOffset, fs.Position);
  4420. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4421. }
  4422. using (var fs = client.OpenRead(remoteFile))
  4423. {
  4424. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4425. Assert.AreEqual(0x04, fs.ReadByte());
  4426. Assert.AreEqual(0x00, fs.ReadByte());
  4427. Assert.AreEqual(0x00, fs.ReadByte());
  4428. var readBuffer = new byte[writeBuffer.Length];
  4429. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4430. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4431. // Ensure we've reached end of the stream
  4432. Assert.AreEqual(-1, fs.ReadByte());
  4433. }
  4434. client.DeleteFile(remoteFile);
  4435. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4436. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4437. // create single-byte file
  4438. using (var fs = client.OpenWrite(remoteFile))
  4439. {
  4440. fs.WriteByte(0x04);
  4441. }
  4442. seekOffset = 550L;
  4443. writeBuffer = GenerateRandom(size: 600);
  4444. using (var fs = client.OpenWrite(remoteFile))
  4445. {
  4446. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4447. Assert.AreEqual(seekOffset, newPosition);
  4448. Assert.AreEqual(seekOffset, fs.Position);
  4449. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4450. }
  4451. using (var fs = client.OpenRead(remoteFile))
  4452. {
  4453. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4454. Assert.AreEqual(0x04, fs.ReadByte());
  4455. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4456. Assert.AreEqual(seekOffset - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4457. Assert.IsTrue(new byte[seekOffset - 1].IsEqualTo(soughtOverReadBuffer));
  4458. var readBuffer = new byte[writeBuffer.Length];
  4459. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4460. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4461. // Ensure we've reached end of the stream
  4462. Assert.AreEqual(-1, fs.ReadByte());
  4463. }
  4464. client.DeleteFile(remoteFile);
  4465. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4466. }
  4467. finally
  4468. {
  4469. if (client.Exists(remoteFile))
  4470. {
  4471. client.DeleteFile(remoteFile);
  4472. }
  4473. }
  4474. }
  4475. }
  4476. [TestMethod]
  4477. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4478. {
  4479. var size = new Random().Next(500, 5000);
  4480. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4481. {
  4482. client.Connect();
  4483. var remoteFile = GenerateUniqueRemoteFileName();
  4484. if (client.Exists(remoteFile))
  4485. {
  4486. client.DeleteFile(remoteFile);
  4487. }
  4488. try
  4489. {
  4490. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4491. {
  4492. s.SetLength(size);
  4493. }
  4494. Assert.IsTrue(client.Exists(remoteFile));
  4495. var attributes = client.GetAttributes(remoteFile);
  4496. Assert.IsTrue(attributes.IsRegularFile);
  4497. Assert.AreEqual(size, attributes.Size);
  4498. using (var downloaded = new MemoryStream())
  4499. {
  4500. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4501. downloaded.Position = 0;
  4502. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4503. }
  4504. }
  4505. finally
  4506. {
  4507. if (client.Exists(remoteFile))
  4508. {
  4509. client.DeleteFile(remoteFile);
  4510. }
  4511. }
  4512. }
  4513. }
  4514. [TestMethod]
  4515. public void Sftp_Open_Append_Write_ExistingFile()
  4516. {
  4517. const int fileSize = 5 * 1024;
  4518. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4519. using (var input = CreateMemoryStream(fileSize))
  4520. {
  4521. input.Position = 0;
  4522. client.Connect();
  4523. var remoteFile = GenerateUniqueRemoteFileName();
  4524. if (client.Exists(remoteFile))
  4525. {
  4526. client.DeleteFile(remoteFile);
  4527. }
  4528. try
  4529. {
  4530. client.UploadFile(input, remoteFile);
  4531. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4532. {
  4533. Assert.IsFalse(s.CanRead);
  4534. Assert.IsTrue(s.CanWrite);
  4535. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4536. s.Write(buffer, offset: 0, buffer.Length);
  4537. input.Write(buffer, offset: 0, buffer.Length);
  4538. }
  4539. using (var downloaded = new MemoryStream())
  4540. {
  4541. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4542. input.Position = 0;
  4543. downloaded.Position = 0;
  4544. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4545. }
  4546. }
  4547. finally
  4548. {
  4549. if (client.Exists(remoteFile))
  4550. {
  4551. client.DeleteFile(remoteFile);
  4552. }
  4553. }
  4554. }
  4555. }
  4556. [TestMethod]
  4557. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4558. {
  4559. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4560. {
  4561. client.Connect();
  4562. var remoteFile = GenerateUniqueRemoteFileName();
  4563. if (client.Exists(remoteFile))
  4564. {
  4565. client.DeleteFile(remoteFile);
  4566. }
  4567. try
  4568. {
  4569. #region Verify if merely opening the file for append creates a zero-byte file
  4570. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4571. {
  4572. }
  4573. Assert.IsTrue(client.Exists(remoteFile));
  4574. var attributes = client.GetAttributes(remoteFile);
  4575. Assert.IsTrue(attributes.IsRegularFile);
  4576. Assert.AreEqual(0L, attributes.Size);
  4577. #endregion Verify if merely opening the file for append creates it
  4578. client.DeleteFile(remoteFile);
  4579. #region Verify if content is actually written to the file
  4580. var content = GenerateRandom(size: 100);
  4581. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4582. {
  4583. s.Write(content, offset: 0, content.Length);
  4584. }
  4585. using (var downloaded = new MemoryStream())
  4586. {
  4587. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4588. downloaded.Position = 0;
  4589. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4590. }
  4591. #endregion Verify if content is actually written to the file
  4592. }
  4593. finally
  4594. {
  4595. if (client.Exists(remoteFile))
  4596. {
  4597. client.DeleteFile(remoteFile);
  4598. }
  4599. }
  4600. }
  4601. }
  4602. [TestMethod]
  4603. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4604. {
  4605. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4606. {
  4607. client.Connect();
  4608. var remoteFile = GenerateUniqueRemoteFileName();
  4609. if (client.Exists(remoteFile))
  4610. {
  4611. client.DeleteFile(remoteFile);
  4612. }
  4613. try
  4614. {
  4615. #region Verify if merely opening the file for create creates a zero-byte file
  4616. using (client.Open(remoteFile, FileMode.Create))
  4617. {
  4618. }
  4619. Assert.IsTrue(client.Exists(remoteFile));
  4620. var attributes = client.GetAttributes(remoteFile);
  4621. Assert.IsTrue(attributes.IsRegularFile);
  4622. Assert.AreEqual(0L, attributes.Size);
  4623. #endregion Verify if merely opening the file for create creates a zero-byte file
  4624. client.DeleteFile(remoteFile);
  4625. #region Verify if content is actually written to the file
  4626. var content = GenerateRandom(size: 100);
  4627. using (var s = client.Open(remoteFile, FileMode.Create))
  4628. {
  4629. Assert.IsTrue(s.CanRead);
  4630. Assert.IsTrue(s.CanWrite);
  4631. s.Write(content, offset: 0, content.Length);
  4632. }
  4633. using (var downloaded = new MemoryStream())
  4634. {
  4635. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4636. downloaded.Position = 0;
  4637. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4638. }
  4639. #endregion Verify if content is actually written to the file
  4640. }
  4641. finally
  4642. {
  4643. if (client.Exists(remoteFile))
  4644. {
  4645. client.DeleteFile(remoteFile);
  4646. }
  4647. }
  4648. }
  4649. }
  4650. [TestMethod]
  4651. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4652. {
  4653. const int fileSize = 5 * 1024;
  4654. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4655. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4656. using (var input = CreateMemoryStream(fileSize))
  4657. {
  4658. client.Connect();
  4659. var remoteFile = GenerateUniqueRemoteFileName();
  4660. if (client.Exists(remoteFile))
  4661. {
  4662. client.DeleteFile(remoteFile);
  4663. }
  4664. try
  4665. {
  4666. input.Position = 0;
  4667. client.UploadFile(input, remoteFile);
  4668. using (var stream = client.Open(remoteFile, FileMode.Create))
  4669. {
  4670. // Verify if merely opening the file for create overwrites the file
  4671. var attributes = client.GetAttributes(remoteFile);
  4672. Assert.IsTrue(attributes.IsRegularFile);
  4673. Assert.AreEqual(0L, attributes.Size);
  4674. stream.Write(newContent, offset: 0, newContent.Length);
  4675. stream.Position = 0;
  4676. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4677. }
  4678. }
  4679. finally
  4680. {
  4681. if (client.Exists(remoteFile))
  4682. {
  4683. client.DeleteFile(remoteFile);
  4684. }
  4685. }
  4686. }
  4687. }
  4688. [TestMethod]
  4689. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4690. {
  4691. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4692. {
  4693. client.Connect();
  4694. var remoteFile = GenerateUniqueRemoteFileName();
  4695. if (client.Exists(remoteFile))
  4696. {
  4697. client.DeleteFile(remoteFile);
  4698. }
  4699. try
  4700. {
  4701. #region Verify if merely opening the file for create creates a zero-byte file
  4702. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4703. {
  4704. }
  4705. Assert.IsTrue(client.Exists(remoteFile));
  4706. var attributes = client.GetAttributes(remoteFile);
  4707. Assert.IsTrue(attributes.IsRegularFile);
  4708. Assert.AreEqual(0L, attributes.Size);
  4709. #endregion Verify if merely opening the file for create creates a zero-byte file
  4710. client.DeleteFile(remoteFile);
  4711. #region Verify if content is actually written to the file
  4712. var content = GenerateRandom(size: 100);
  4713. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4714. {
  4715. s.Write(content, offset: 0, content.Length);
  4716. }
  4717. using (var downloaded = new MemoryStream())
  4718. {
  4719. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4720. downloaded.Position = 0;
  4721. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4722. }
  4723. #endregion Verify if content is actually written to the file
  4724. }
  4725. finally
  4726. {
  4727. if (client.Exists(remoteFile))
  4728. {
  4729. client.DeleteFile(remoteFile);
  4730. }
  4731. }
  4732. }
  4733. }
  4734. [TestMethod]
  4735. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4736. {
  4737. const int fileSize = 5 * 1024;
  4738. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4739. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4740. using (var input = CreateMemoryStream(fileSize))
  4741. {
  4742. client.Connect();
  4743. var remoteFile = GenerateUniqueRemoteFileName();
  4744. if (client.Exists(remoteFile))
  4745. {
  4746. client.DeleteFile(remoteFile);
  4747. }
  4748. try
  4749. {
  4750. input.Position = 0;
  4751. client.UploadFile(input, remoteFile);
  4752. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4753. {
  4754. // Verify if merely opening the file for create overwrites the file
  4755. var attributes = client.GetAttributes(remoteFile);
  4756. Assert.IsTrue(attributes.IsRegularFile);
  4757. Assert.AreEqual(0L, attributes.Size);
  4758. stream.Write(newContent, offset: 0, newContent.Length);
  4759. stream.Position = 0;
  4760. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4761. }
  4762. }
  4763. finally
  4764. {
  4765. if (client.Exists(remoteFile))
  4766. {
  4767. client.DeleteFile(remoteFile);
  4768. }
  4769. }
  4770. }
  4771. }
  4772. [TestMethod]
  4773. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4774. {
  4775. // use new content that contains less bytes than original content to
  4776. // verify whether file is first truncated
  4777. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4778. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4779. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4780. {
  4781. client.Connect();
  4782. var remoteFile = GenerateUniqueRemoteFileName();
  4783. if (client.Exists(remoteFile))
  4784. {
  4785. client.DeleteFile(remoteFile);
  4786. }
  4787. try
  4788. {
  4789. client.WriteAllBytes(remoteFile, originalContent);
  4790. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4791. {
  4792. s.Write(newContent, offset: 0, newContent.Length);
  4793. }
  4794. using (var downloaded = new MemoryStream())
  4795. {
  4796. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4797. downloaded.Position = 0;
  4798. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4799. }
  4800. }
  4801. finally
  4802. {
  4803. if (client.Exists(remoteFile))
  4804. {
  4805. client.DeleteFile(remoteFile);
  4806. }
  4807. }
  4808. }
  4809. }
  4810. [TestMethod]
  4811. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4812. {
  4813. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4814. {
  4815. client.Connect();
  4816. var remoteFile = GenerateUniqueRemoteFileName();
  4817. if (client.Exists(remoteFile))
  4818. {
  4819. client.DeleteFile(remoteFile);
  4820. }
  4821. try
  4822. {
  4823. #region Verify if merely opening the file for create creates a zero-byte file
  4824. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4825. {
  4826. }
  4827. Assert.IsTrue(client.Exists(remoteFile));
  4828. var attributes = client.GetAttributes(remoteFile);
  4829. Assert.IsTrue(attributes.IsRegularFile);
  4830. Assert.AreEqual(0L, attributes.Size);
  4831. #endregion Verify if merely opening the file for create creates a zero-byte file
  4832. client.DeleteFile(remoteFile);
  4833. #region Verify if content is actually written to the file
  4834. var content = GenerateRandom(size: 100);
  4835. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4836. {
  4837. s.Write(content, offset: 0, content.Length);
  4838. }
  4839. using (var downloaded = new MemoryStream())
  4840. {
  4841. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4842. downloaded.Position = 0;
  4843. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4844. }
  4845. #endregion Verify if content is actually written to the file
  4846. }
  4847. finally
  4848. {
  4849. if (client.Exists(remoteFile))
  4850. {
  4851. client.DeleteFile(remoteFile);
  4852. }
  4853. }
  4854. }
  4855. }
  4856. [TestMethod]
  4857. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4858. {
  4859. const int fileSize = 5 * 1024;
  4860. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4861. using (var input = CreateMemoryStream(fileSize))
  4862. {
  4863. client.Connect();
  4864. var remoteFile = GenerateUniqueRemoteFileName();
  4865. if (client.Exists(remoteFile))
  4866. {
  4867. client.DeleteFile(remoteFile);
  4868. }
  4869. input.Position = 0;
  4870. try
  4871. {
  4872. client.UploadFile(input, remoteFile);
  4873. Stream stream = null;
  4874. try
  4875. {
  4876. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4877. Assert.Fail();
  4878. }
  4879. catch (SshException)
  4880. {
  4881. }
  4882. finally
  4883. {
  4884. stream?.Dispose();
  4885. }
  4886. // Verify that the file was not modified
  4887. using (var downloaded = new MemoryStream())
  4888. {
  4889. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4890. input.Position = 0;
  4891. downloaded.Position = 0;
  4892. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4893. }
  4894. }
  4895. finally
  4896. {
  4897. if (client.Exists(remoteFile))
  4898. {
  4899. client.DeleteFile(remoteFile);
  4900. }
  4901. }
  4902. }
  4903. }
  4904. [TestMethod]
  4905. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4906. {
  4907. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4908. {
  4909. client.Connect();
  4910. var remoteFile = GenerateUniqueRemoteFileName();
  4911. if (client.Exists(remoteFile))
  4912. {
  4913. client.DeleteFile(remoteFile);
  4914. }
  4915. try
  4916. {
  4917. #region Verify if merely opening the file creates a zero-byte file
  4918. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4919. {
  4920. }
  4921. Assert.IsTrue(client.Exists(remoteFile));
  4922. var attributes = client.GetAttributes(remoteFile);
  4923. Assert.IsTrue(attributes.IsRegularFile);
  4924. Assert.AreEqual(0L, attributes.Size);
  4925. #endregion Verify if merely opening the file creates it
  4926. client.DeleteFile(remoteFile);
  4927. #region Verify if content is actually written to the file
  4928. var content = GenerateRandom(size: 100);
  4929. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4930. {
  4931. s.Write(content, offset: 0, content.Length);
  4932. }
  4933. using (var downloaded = new MemoryStream())
  4934. {
  4935. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4936. downloaded.Position = 0;
  4937. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4938. }
  4939. #endregion Verify if content is actually written to the file
  4940. }
  4941. finally
  4942. {
  4943. if (client.Exists(remoteFile))
  4944. {
  4945. client.DeleteFile(remoteFile);
  4946. }
  4947. }
  4948. }
  4949. }
  4950. [TestMethod]
  4951. public void Sftp_Open_Open_Write_ExistingFile()
  4952. {
  4953. // use new content that contains less bytes than original content to
  4954. // verify whether file is first truncated
  4955. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4956. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4957. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4958. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4959. {
  4960. client.Connect();
  4961. var remoteFile = GenerateUniqueRemoteFileName();
  4962. if (client.Exists(remoteFile))
  4963. {
  4964. client.DeleteFile(remoteFile);
  4965. }
  4966. try
  4967. {
  4968. client.WriteAllBytes(remoteFile, originalContent);
  4969. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4970. {
  4971. s.Write(newContent, offset: 0, newContent.Length);
  4972. }
  4973. using (var downloaded = new MemoryStream())
  4974. {
  4975. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4976. downloaded.Position = 0;
  4977. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4978. }
  4979. }
  4980. finally
  4981. {
  4982. if (client.Exists(remoteFile))
  4983. {
  4984. client.DeleteFile(remoteFile);
  4985. }
  4986. }
  4987. }
  4988. }
  4989. [TestMethod]
  4990. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4991. {
  4992. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4993. {
  4994. client.Connect();
  4995. var remoteFile = GenerateUniqueRemoteFileName();
  4996. if (client.Exists(remoteFile))
  4997. {
  4998. client.DeleteFile(remoteFile);
  4999. }
  5000. try
  5001. {
  5002. Stream stream = null;
  5003. try
  5004. {
  5005. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  5006. Assert.Fail();
  5007. }
  5008. catch (SshException)
  5009. {
  5010. }
  5011. finally
  5012. {
  5013. stream?.Dispose();
  5014. }
  5015. Assert.IsFalse(client.Exists(remoteFile));
  5016. }
  5017. finally
  5018. {
  5019. if (client.Exists(remoteFile))
  5020. {
  5021. client.DeleteFile(remoteFile);
  5022. }
  5023. }
  5024. }
  5025. }
  5026. [TestMethod]
  5027. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  5028. {
  5029. // use new content that contains less bytes than original content to
  5030. // verify whether file is first truncated
  5031. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  5032. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  5033. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  5034. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5035. {
  5036. client.Connect();
  5037. var remoteFile = GenerateUniqueRemoteFileName();
  5038. if (client.Exists(remoteFile))
  5039. {
  5040. client.DeleteFile(remoteFile);
  5041. }
  5042. try
  5043. {
  5044. client.WriteAllBytes(remoteFile, originalContent);
  5045. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  5046. {
  5047. s.Write(newContent, offset: 0, newContent.Length);
  5048. }
  5049. using (var downloaded = new MemoryStream())
  5050. {
  5051. DownloadFileRandomMethod(client, remoteFile, downloaded);
  5052. downloaded.Position = 0;
  5053. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  5054. }
  5055. }
  5056. finally
  5057. {
  5058. if (client.Exists(remoteFile))
  5059. {
  5060. client.DeleteFile(remoteFile);
  5061. }
  5062. }
  5063. }
  5064. }
  5065. [TestMethod]
  5066. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  5067. {
  5068. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5069. {
  5070. client.Connect();
  5071. var remoteFile = GenerateUniqueRemoteFileName();
  5072. if (client.Exists(remoteFile))
  5073. {
  5074. client.DeleteFile(remoteFile);
  5075. }
  5076. try
  5077. {
  5078. #region Verify if merely opening the file creates a zero-byte file
  5079. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  5080. {
  5081. }
  5082. Assert.IsTrue(client.Exists(remoteFile));
  5083. var attributes = client.GetAttributes(remoteFile);
  5084. Assert.IsTrue(attributes.IsRegularFile);
  5085. Assert.AreEqual(0L, attributes.Size);
  5086. #endregion Verify if merely opening the file creates it
  5087. client.DeleteFile(remoteFile);
  5088. #region Verify if content is actually written to the file
  5089. var content = GenerateRandom(size: 100);
  5090. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  5091. {
  5092. s.Write(content, offset: 0, content.Length);
  5093. }
  5094. using (var downloaded = new MemoryStream())
  5095. {
  5096. DownloadFileRandomMethod(client, remoteFile, downloaded);
  5097. downloaded.Position = 0;
  5098. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  5099. }
  5100. #endregion Verify if content is actually written to the file
  5101. }
  5102. finally
  5103. {
  5104. if (client.Exists(remoteFile))
  5105. {
  5106. client.DeleteFile(remoteFile);
  5107. }
  5108. }
  5109. }
  5110. }
  5111. [TestMethod]
  5112. public void Sftp_Open_Truncate_Write_ExistingFile()
  5113. {
  5114. const int fileSize = 5 * 1024;
  5115. // use new content that contains less bytes than original content to
  5116. // verify whether file is first truncated
  5117. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  5118. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  5119. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5120. using (var input = CreateMemoryStream(fileSize))
  5121. {
  5122. client.Connect();
  5123. var remoteFile = GenerateUniqueRemoteFileName();
  5124. if (client.Exists(remoteFile))
  5125. {
  5126. client.DeleteFile(remoteFile);
  5127. }
  5128. input.Position = 0;
  5129. try
  5130. {
  5131. client.WriteAllBytes(remoteFile, originalContent);
  5132. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  5133. {
  5134. s.Write(newContent, offset: 0, newContent.Length);
  5135. }
  5136. using (var downloaded = new MemoryStream())
  5137. {
  5138. DownloadFileRandomMethod(client, remoteFile, downloaded);
  5139. input.Position = 0;
  5140. downloaded.Position = 0;
  5141. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  5142. }
  5143. }
  5144. finally
  5145. {
  5146. if (client.Exists(remoteFile))
  5147. {
  5148. client.DeleteFile(remoteFile);
  5149. }
  5150. }
  5151. }
  5152. }
  5153. [TestMethod]
  5154. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  5155. {
  5156. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5157. {
  5158. client.Connect();
  5159. var remoteFile = GenerateUniqueRemoteFileName();
  5160. if (client.Exists(remoteFile))
  5161. {
  5162. client.DeleteFile(remoteFile);
  5163. }
  5164. try
  5165. {
  5166. Stream stream = null;
  5167. try
  5168. {
  5169. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  5170. Assert.Fail();
  5171. }
  5172. catch (SshException)
  5173. {
  5174. }
  5175. Assert.IsFalse(client.Exists(remoteFile));
  5176. }
  5177. finally
  5178. {
  5179. if (client.Exists(remoteFile))
  5180. {
  5181. client.DeleteFile(remoteFile);
  5182. }
  5183. }
  5184. }
  5185. }
  5186. [TestMethod]
  5187. public void Sftp_SetLastAccessTime()
  5188. {
  5189. var testFilePath = "/home/sshnet/test-file.txt";
  5190. var testContent = "File";
  5191. using var client = new SftpClient(_connectionInfoFactory.Create());
  5192. client.Connect();
  5193. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5194. client.UploadFile(fileStream, testFilePath);
  5195. try
  5196. {
  5197. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5198. client.SetLastAccessTime(testFilePath, newTime);
  5199. var time = client.GetLastAccessTime(testFilePath);
  5200. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5201. }
  5202. finally
  5203. {
  5204. client.DeleteFile(testFilePath);
  5205. }
  5206. }
  5207. [TestMethod]
  5208. public void Sftp_SetLastAccessTimeUtc()
  5209. {
  5210. var testFilePath = "/home/sshnet/test-file.txt";
  5211. var testContent = "File";
  5212. using var client = new SftpClient(_connectionInfoFactory.Create());
  5213. client.Connect();
  5214. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5215. client.UploadFile(fileStream, testFilePath);
  5216. try
  5217. {
  5218. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5219. client.SetLastAccessTimeUtc(testFilePath, newTime);
  5220. var time = client.GetLastAccessTimeUtc(testFilePath);
  5221. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5222. }
  5223. finally
  5224. {
  5225. client.DeleteFile(testFilePath);
  5226. }
  5227. }
  5228. [TestMethod]
  5229. public void Sftp_SetLastWriteTime()
  5230. {
  5231. var testFilePath = "/home/sshnet/test-file.txt";
  5232. var testContent = "File";
  5233. using var client = new SftpClient(_connectionInfoFactory.Create());
  5234. client.Connect();
  5235. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5236. client.UploadFile(fileStream, testFilePath);
  5237. try
  5238. {
  5239. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5240. client.SetLastWriteTime(testFilePath, newTime);
  5241. var time = client.GetLastWriteTime(testFilePath);
  5242. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5243. }
  5244. finally
  5245. {
  5246. client.DeleteFile(testFilePath);
  5247. }
  5248. }
  5249. [TestMethod]
  5250. public void Sftp_SetLastWriteTimeUtc()
  5251. {
  5252. var testFilePath = "/home/sshnet/test-file.txt";
  5253. var testContent = "File";
  5254. using var client = new SftpClient(_connectionInfoFactory.Create());
  5255. client.Connect();
  5256. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5257. client.UploadFile(fileStream, testFilePath);
  5258. try
  5259. {
  5260. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5261. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5262. var time = client.GetLastWriteTimeUtc(testFilePath);
  5263. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5264. }
  5265. finally
  5266. {
  5267. client.DeleteFile(testFilePath);
  5268. }
  5269. }
  5270. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5271. {
  5272. yield return new object[] { 0 };
  5273. yield return new object[] { 5 * 1024 * 1024 };
  5274. }
  5275. private static Encoding GetRandomEncoding()
  5276. {
  5277. var random = new Random().Next(1, 4);
  5278. switch (random)
  5279. {
  5280. case 1:
  5281. return Encoding.Unicode;
  5282. case 2:
  5283. return Encoding.UTF8;
  5284. default:
  5285. Debug.Assert(random == 3);
  5286. return Encoding.UTF32;
  5287. }
  5288. }
  5289. private void DownloadFileRandomMethod(SftpClient client, string path, Stream output)
  5290. {
  5291. Console.Write($"Downloading '{path}'");
  5292. var random = new Random().Next(1, 6);
  5293. switch (random)
  5294. {
  5295. case 1:
  5296. Console.WriteLine($" with {nameof(SftpClient.DownloadFile)}");
  5297. client.DownloadFile(path, output);
  5298. break;
  5299. case 2:
  5300. Console.WriteLine($" with {nameof(SftpClient.DownloadFileAsync)}");
  5301. client.DownloadFileAsync(path, output).GetAwaiter().GetResult();
  5302. break;
  5303. case 3:
  5304. Console.WriteLine($" with {nameof(SftpClient.BeginDownloadFile)}");
  5305. client.EndDownloadFile(client.BeginDownloadFile(path, output));
  5306. break;
  5307. case 4:
  5308. Console.WriteLine($" with {nameof(SftpFileStream.CopyTo)}");
  5309. using (var fs = client.OpenRead(path))
  5310. {
  5311. fs.CopyTo(output);
  5312. }
  5313. break;
  5314. default:
  5315. Debug.Assert(random == 5);
  5316. Console.WriteLine($" with {nameof(SftpFileStream.CopyToAsync)}");
  5317. using (var fs = client.OpenAsync(path, FileMode.Open, FileAccess.Read, CancellationToken.None).GetAwaiter().GetResult())
  5318. {
  5319. fs.CopyToAsync(output).GetAwaiter().GetResult();
  5320. }
  5321. break;
  5322. }
  5323. }
  5324. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5325. {
  5326. var preamble = encoding.GetPreamble();
  5327. var textBytes = encoding.GetBytes(text);
  5328. if (preamble.Length != 0)
  5329. {
  5330. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5331. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5332. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5333. return textAndPreambleBytes;
  5334. }
  5335. return textBytes;
  5336. }
  5337. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5338. {
  5339. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5340. }
  5341. private static void SftpCreateRemoteFile(SftpClient client, string remoteFile, int size)
  5342. {
  5343. var file = CreateTempFile(size);
  5344. try
  5345. {
  5346. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  5347. {
  5348. client.UploadFile(fs, remoteFile);
  5349. }
  5350. }
  5351. finally
  5352. {
  5353. File.Delete(file);
  5354. }
  5355. }
  5356. private static byte[] GenerateRandom(int size)
  5357. {
  5358. var random = new Random();
  5359. var randomContent = new byte[size];
  5360. random.NextBytes(randomContent);
  5361. return randomContent;
  5362. }
  5363. private static Stream CreateStreamWithContent(string content)
  5364. {
  5365. var memoryStream = new MemoryStream();
  5366. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5367. sw.Write(content);
  5368. sw.Flush();
  5369. memoryStream.Position = 0;
  5370. return memoryStream;
  5371. }
  5372. private static string GenerateUniqueRemoteFileName()
  5373. {
  5374. return $"/home/sshnet/{Guid.NewGuid():D}";
  5375. }
  5376. }
  5377. }